// 当前系统接口域名
var baseUrl = 'http://jsyc-server.jsyc:9105/';

var identifyApiUrl = 'http://127.0.0.1:9090/ky/api/';//技术分析api地址
var apipwd='GH850udHF1SIK2EWEODBFRJQiXJaY=:8953070c-90e3-4c3f-0c82-34fe514957e1';//楼口密码

var powerToken = '';//统一身份登录参数
var ssoUrl = '';//点登录系统登录页面url 

 
let urlParams = getUrlParams(window.location.search);
if (urlParams.powerToken){
    powerToken = urlParams.powerToken
}

if (urlParams.ssoUrl) {
   ssoUrl = urlParams.ssoUrl;
   localStorage.setItem('ssoUrl', ssoUrl);
}
 
// if (window.location.search.indexOf('powerToken') !== -1) {
//   powerToken = window.location.search.split('powerToken=')[1];
// }
// if (window.location.search.indexOf('ssoUrl') !== -1) {
//   ssoUrl = window.location.search.split('ssoUrl=')[1];
//   localStorage.setItem('ssoUrl', ssoUrl);
// }


function getUrlParams(url) {
  const params = {};
  const regex = /[?&]([^=#]+)=([^&#]*)/g;
  let match;
  while((match = regex.exec(url)) !== null) {
    const key = decodeURIComponent(match[1]);
    const value = decodeURIComponent(match[2]);
    params[key] = value;
  }
  return params;
}


function testRequest(url, method, data) {
   return new Promise((resolve, reject) => { 
    const xhr = new XMLHttpRequest();
    xhr.open(method,  url, true);
    xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
    xhr.setRequestHeader('apipwd', apipwd); 
    xhr.onreadystatechange = function () {

      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          resolve(JSON.parse(xhr.responseText));
        } else { 
          reject(new Error('请求失败，状态码：' + xhr.status));
        } 
      }
    };
    xhr.send(JSON.stringify(data));
  });
}
 
//同步技术点标识
function syncIdentify(themeList){ 
  testRequest(identifyApiUrl + 'common/keytech/add', 'post', {"techContent": JSON.stringify(themeList)}).then(data => {
    console.log(data);
  }).catch(error => {
    console.error(error);
  });
}

function showLoading(){
  //展示加载中样式
  let loading = document.getElementById('global-loading');
  if (!loading) {
    loading = document.createElement('div');
    loading.id = 'global-loading';
    loading.className = 'loading';
    loading.innerHTML = '<div class="spinner"></div>';
    // 添加全屏样式
    loading.style.position = 'fixed';
    loading.style.top = '0';
    loading.style.left = '0';
    loading.style.width = '100%';
    loading.style.height = '100%';
    loading.style.backgroundColor = 'rgba(255, 255, 255, 0.8)';
    loading.style.zIndex = '999999';
    loading.style.display = 'flex';
    loading.style.justifyContent = 'center';
    loading.style.alignItems = 'center';
    document.body.appendChild(loading);
  } else {
    loading.style.display = 'flex';
  }
  
  // 添加spinner样式
  const spinner = loading.querySelector('.spinner');
  spinner.style.width = '50px';
  spinner.style.height = '50px';
  spinner.style.border = '5px solid #f3f3f3';
  spinner.style.borderTop = '5px solid #1E9FFF';
  spinner.style.borderRadius = '50%';
  spinner.style.animation = 'spin 1s linear infinite';
  
  // 添加旋转动画
  if (!document.getElementById('spinner-animation')) {
    const style = document.createElement('style');
    style.id = 'spinner-animation';
    style.textContent = '@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }';
    document.head.appendChild(style);
  }
}
 
function hideLoading(){
  //隐藏加载中样式
  const loading = document.getElementById('global-loading');
  if (loading) {
    loading.style.display = 'none';
  }
}
 
//获取数据源
function getFileList(){ 
  showLoading();
   testRequest(identifyApiUrl + 'common/getFilelist', 'get',{}
  ).then(data => {
    console.log(data);
    //同步数据库
     request('api/DataBase/saveDataSource', 'POST', {records:data.records}).then(data => {
        if (data.code === 1) {
          hideLoading();
          showMessage('添加数据源成功', 'success');
        } else {
          hideLoading();
           showMessage('添加数据源失败', 'error');
        }
      }).catch(error => {
        hideLoading();
        showMessage('添加数据源失败', 'error');
      });

  }).catch(error => {
    hideLoading();
    showMessage('添加数据源失败', 'error');
  });
}
 
//数据源详情
function getFileDetail(id = ''){
  showLoading();
   testRequest(identifyApiUrl + 'common/outside/file?id='+id, 'get',{}
  ).then(data => {
    console.log(data);
    //更新详情
    request('api/DataBase/updateDataSourceDetail', 'POST', {id:id, detail:data.data.detail}).then(data => {
      if (data.code === 1) {
        hideLoading();
        showMessage('更新数据源详情成功', 'success');
      } else {
        hideLoading();
        showMessage('更新数据源详情失败', 'error');
      }
    }).catch(error => {
      hideLoading();
      showMessage('更新数据源详情失败', 'error');
    });
    hideLoading();
  }).catch(error => {
    hideLoading();
    console.error(error);
  });
}
 


//检查sso登录是否过期
function checkSsoLogin() { 
  
  if (localStorage.getItem('powerToken') && localStorage.getItem('token')) {
    request('api/ApiUser/thirdSsoLogin', 'POST', {
        saToken:localStorage.getItem('powerToken')
      }).then(data => {
        if (data.code === 1) {
             
        } else {
            showMessage('登录过期，请重新登录！', 'error'); 
            localStorage.clear(); 
            setTimeout(() => {
              ssoUrl ? window.location.href = ssoUrl : '';
            }, 2000);
        }
      }).catch(error => {
            showMessage('登录过期，请重新登录！', 'error'); 
            localStorage.clear(); 
            setTimeout(() => {
              ssoUrl ? window.location.href = ssoUrl : '';
            }, 2000);
      });
  }
}
 

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function () {
  if (localStorage.getItem('user_name')) {
    const userNameElement = document.getElementById('user-name');
    if (userNameElement) {
      userNameElement.textContent = localStorage.getItem('user_name');
    }
  }
  if (localStorage.getItem('user_avatar')) {
    const userAvatarElement = document.getElementById('user-avatar');
    if (userAvatarElement) {
      userAvatarElement.src = baseUrl + localStorage.getItem('user_avatar');
    }
    const userAvatarPreview = document.getElementById('user-avatar-preview');
    if (userAvatarPreview) {
      userAvatarPreview.src = baseUrl + localStorage.getItem('user_avatar');
    }
  }
  
  

  if (powerToken) {  
      //调用后台请求单点登录
      request('api/ApiUser/thirdSsoLogin', 'POST', {
        saToken:powerToken
      }).then(data => {
        if (data.code === 1) {
            let ssoId = data.data.ssoId;//根据实际接口返回赋值
            loginSystem(ssoId, powerToken);
        } else {
            showMessage('登录失败！', 'error');
            localStorage.clear();
            setTimeout(() => {
             ssoUrl ? window.location.href = ssoUrl : '';
           }, 2000);
        }
      }).catch(error => {
            showMessage('登录失败！', 'error');
            localStorage.clear();
            setTimeout(() => {
             ssoUrl ? window.location.href = ssoUrl : '';
           }, 2000);
      });
       
  } else {
    // 初始化应用
    initApp();
    // 绑定通用事件
    bindCommonEvents();
    // 绑定页签切换事件
    bindTabEvents();
    // 为评估页面绑定采用和忽略按钮事件（如果在评估页面）
    if (document.body.dataset.page === 'evaluation') {
      bindAdoptIgnoreButtons();
    }
  }
});
//sso登录成功之后，登录本系统
function loginSystem(ssoId = '', powerToken = '') {
  // debugger
  //调用登录接口 ssoId加密
  // let newSsoId = base64_encode(ssoId);//怎么加密php后台可以解密 
  request('api/ApiUser/userSsoLogin', 'POST', { ssoId: ssoId }).then(data => {
    if (data.code === 1) {
      localStorage.setItem('powerToken', powerToken);
      // 登录成功，保存token 
      localStorage.setItem('token', data.data.token);
      // 保存用户类型
      localStorage.setItem('user_type', data.data.user_type);
      localStorage.setItem('user_name', data.data.user_name);
      localStorage.setItem('user_avatar', data.data.user_avatar);

      //如果是普通用户跳转评估页面
      if (data.data.user_type == 2) {
        window.location.assign('evaluation.html');
      } else {
        // 跳转到首页
        window.location.href = 'index.html';
      }
      // 初始化应用
      initApp();
      // 绑定通用事件
      bindCommonEvents();
      // 绑定页签切换事件
      bindTabEvents();
      // 为评估页面绑定采用和忽略按钮事件（如果在评估页面）
      if (document.body.dataset.page === 'evaluation') {
        bindAdoptIgnoreButtons();
      }
      //获取用户信息登录当前系统
      initUserInfo();
    } else {
      showMessage(data.msg, 'error');
    }
  }).catch(error => {
    showMessage('登录失败！！', 'error');
    setTimeout(() => {
      ssoUrl ? window.location.href = ssoUrl : '';
    }, 3000);
  });
}

//更新用户信息
function updateUserInfo(avatar) {
  request('api/ApiUser/updateUser', 'POST', { avatar: avatar }).then(data => {
    if (data.code === 1) {
      initUserInfo();
    } else {
    }
  }).catch(error => {
  });
}

//上传头像
function uploadAvatar() {
  //获取文件
  const fileInput = document.getElementById('avatar-upload-input');
  const file = fileInput.files[0];
  if (!file) {
    showMessage('请选择要上传的文件！', 'error');
    return;
  }
  //创建表单数据
  const formData = new FormData();
  formData.append('file', file);
  // 发送请求，移除 Content-Type 请求头，让浏览器自动设置以正确处理 FormData
  const xhr = new XMLHttpRequest();
  xhr.open('POST', baseUrl + 'api/upload/index', true);
  xhr.setRequestHeader('method', 'tkh5');
  const token = localStorage.getItem('token');
  if (token) {
    xhr.setRequestHeader('token', token);
  }
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        try {
          const data = JSON.parse(xhr.responseText);
          if (data.code === 1) {
            // 上传成功，更新头像
            const avatarUrl = data.data;
            updateUserInfo(avatarUrl);
            showMessage('上传成功', 'success');
          } else {
            showMessage(data.msg, 'error');
          }
        } catch (parseError) {
          console.error('解析响应数据失败:', parseError);
        }
      } else {
        console.error('上传失败，状态码：', xhr.status);
      }
    }
  };
  xhr.send(formData);
  //清空文件输入框
  fileInput.value = '';
}

//修改密码
function changePassword() {
  //清空表单 
  const form = document.getElementById('change-password-form');
  const formData = new FormData(form);
  const data = Object.fromEntries(formData.entries());
  //判断旧密码是否为空
  if (!data.oldPassword) {
    showMessage('旧密码不能为空', 'error');
    return;
  }
  //判断新密码是否为空
  if (!data.newPassword) {
    showMessage('新密码不能为空', 'error');
    return;
  }
  //判断确认新密码是否为空
  if (!data.confirmPassword) {
    showMessage('确认新密码不能为空', 'error');
    return;
  }
  //判断新密码和确认新密码是否一致
  if (data.newPassword !== data.confirmPassword) {
    showMessage('新密码和确认新密码不一致', 'error');
    return;
  }

  request('api/ApiUser/changePassword', 'POST', data).then(data => {
    if (data.code === 1) {
      showMessage('修改密码成功', 'success');
      closePwdModal();

    } else {
      showMessage(data.msg, 'error');
    }
  }).catch(error => {
    console.error('修改密码失败:', error);
  });
}

//退出登录
function logout() {
  showConfirmModal(`确定要退出登录吗？`, function () {
    
    //调用sso退出接口
    
    request('api/ApiUser/thirdSsoLoginOut', 'POST', {saToken:localStorage.getItem('powerToken')}).then(data => {
        if (data.code === 1) {
          let ssourl = localStorage.getItem('ssoUrl');
          showMessage('退出登录成功', 'success');
          localStorage.removeItem('token');
          localStorage.removeItem('powerToken'); 
          localStorage.clear();
          
          setTimeout(() => {
            ssourl ? window.location.href = ssourl : '/';
          }, 3000);
        } else {
          showMessage('退出登录失败！', 'error');
        }
      }).catch(error => {
        showMessage('退出登录失败！', 'error'); 
       });

    // ssoRequest(ssoApiUrl + 'user/logout', 'GET').then(data => { }).catch(error => { });
    // ssoCorsRequest(ssoApiUrl + 'user/logout', 'GET').then(data => { }).catch(error => { });
    //  window.location.href = ssoUrl ? ssoUrl : 'login.html';
  });
}

function addAdminUser() {
  //获取参数
  const form = document.getElementById('add-admin-form');
  const formData = new FormData(form);
  const data = Object.fromEntries(formData.entries());
  //判断用户名是否为空
  if (!data.username) {
    showMessage('用户名不能为空', 'error');
    return;
  }
  //判断密码是否为空
  if (!data.password) {
    showMessage('密码不能为空', 'error');
    return;
  }
  request('api/ApiUser/createAccount', 'POST', {
    user_name: data.username,
    type: 1,
    password: data.password,
    ssoId: data.ssoId,
  }).then(data => {
    if (data.code === 1) {
      showMessage('添加管理员成功', 'success');
      closeAddAdminModal();
      //刷新管理员列表
      initExpertList();
    } else {
      showMessage(data.msg, 'error');
    }
  }).catch(error => {
    console.error('添加管理员失败:', error);
  });
}

//添加专家提交
function addExpertUser() {
  //获取参数
  const form = document.getElementById('add-expert-form');
  const formData = new FormData(form);
  const data = Object.fromEntries(formData.entries());
  //判断用户名是否为空
  if (!data.username) {
    showMessage('用户名不能为空', 'error');
    return;
  }
  //判断密码是否为空
  if (!data.password) {
    showMessage('密码不能为空', 'error');
    return;
  }
  request('api/ApiUser/createAccount', 'POST', {
    user_name: data.username,
    password: data.password,
    type: 2,
    ssoId: data.ssoId,
  }).then(data => {
    if (data.code === 1) {
      showMessage('添加专家成功', 'success');
      closeAddExpertModal();
      //刷新专家列表
      initExpertList();
    } else {
      showMessage(data.msg, 'error');
    }
  }).catch(error => {
    console.error('添加专家失败:', error);
  });
}

//添加管理员
function addAdmin() {
  //清空表单
  const form = document.getElementById('add-admin-form');
  form.reset();

  const modal = document.getElementById('add-admin-modal');
  modal.style.display = '';
}

//添加专家
function addExpert() {
  //清空表单
  const form = document.getElementById('add-expert-form');
  form.reset();

  const modal = document.getElementById('add-expert-modal');
  modal.style.display = '';
}

//关闭添加管理员
function closeAddAdminModal() {
  const modal = document.getElementById('add-admin-modal');
  modal.style.display = 'none';
}

//关闭添加专家弹框
function closeAddExpertModal() {
  const modal = document.getElementById('add-expert-modal');
  modal.style.display = 'none';
}


//显示密码弹框
function showPwdModal() {
  //清空表单
  const form = document.getElementById('change-password-form');
  form.reset();

  const modal = document.getElementById('pwd-modal');
  modal.style.display = '';
}

//关闭密码弹框
function closePwdModal() {
  const modal = document.getElementById('pwd-modal');
  modal.style.display = 'none';
}

//初始化用户信息
function initUserInfo() {
  request('api/ApiUser/getUserInfo', 'POST', {}).then(data => {
    if (data.code === 1) {
      localStorage.setItem('user_name', data.data.user_name);
      localStorage.setItem('user_avatar', data.data.avatar);

      document.getElementById('user-name').textContent = localStorage.getItem('user_name');
      document.getElementById('user-avatar').src = baseUrl + localStorage.getItem('user_avatar');
      document.getElementById('user-avatar-preview').src = baseUrl + localStorage.getItem('user_avatar');

    } else {
      showMessage(data.msg, 'error');
    }
  }).catch(error => {
    console.error('获取用户信息失败:', error);
  });
}

function openEditExpertModal(expert) {

  // 填充专家信息到编辑表单
  document.getElementById('edit-expert-id').value = expert.user_id || '';
  document.getElementById('edit-expert-username').value = expert.user_name || '';
  document.getElementById('edit-expert-ssoId').value = expert.ssoId || '';
  document.getElementById('edit-expert-password').value = '';

  // 显示编辑专家弹框
  const modal = document.getElementById('edit-expert-modal');
  modal.style.display = '';
}

function closeEditExpertModal() {
  const modal = document.getElementById('edit-expert-modal');
  modal.style.display = 'none';
}

function initExpertDataFun() {
  request('api/ApiUser/getExpertList', 'POST', { type: 2 }).then(data => {
    if (data.code === 1) {
      // 根据id expert-list 组装专家列表包括头像 昵称 添加日期
      const expertList = data.data;
      const expertListContainer = document.getElementById('expert-list');
      expertListContainer.innerHTML = '';
      expertList.forEach(expert => {
        const expertItem = document.createElement('div');
        expertItem.className = 'expert-item';
        // 设置专家项样式，添加边距、边框、圆角和阴影效果
        expertItem.style.display = 'flex';
        expertItem.style.alignItems = 'center';
        expertItem.style.padding = '12px 16px';
        expertItem.style.marginBottom = '10px';
        expertItem.style.border = '1px solid #e0e0e0';
        expertItem.style.borderRadius = '6px';
        expertItem.style.backgroundColor = '#fff';
        expertItem.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.1)';
        expertItem.style.transition = 'all 0.3s ease';
        expertItem.onmouseenter = () => {
          expertItem.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.15)';
        };
        expertItem.onmouseleave = () => {
          expertItem.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.1)';
        };

        expertItem.innerHTML = `
          <img src="${expert.avatar ? baseUrl + expert.avatar : 'default_avatar.png'}" alt="${expert.user_name}" style="
            width: 48px;
            height: 48px;
            border-radius: 50%;
            margin-right: 16px;
            object-fit: cover;
          ">
          <div style="flex: 1;">
            <p style="margin: 0 0 4px 0; font-size: 16px; font-weight: bold; color: #333;">${expert.user_name}</p>
            <p style="margin: 0; font-size: 14px; color: #666;">${expert.create_time}</p>
          </div>

           
          <button class="edit-expert-btn" style="
            padding: 6px 12px;
            margin-right: 8px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
          ">编辑</button>

        
         
          <button class="delete-expert-btn" style="
            padding: 6px 12px;
            background-color: #ff4444;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
          ">删除</button>
        `;

        // 绑定编辑按钮点击事件
        const editBtn = expertItem.querySelector('.edit-expert-btn');
        if (editBtn) {
          editBtn.addEventListener('click', () => {
            // 实际开发中这里应替换为真实的编辑请求逻辑
            // console.log(`准备编辑专家: ${expert.user_name}, ID: ${expert.user_id || '未知'}`);
            //打开编辑专家弹框
            openEditExpertModal(expert);
          });
        }

        // 绑定删除按钮点击事件
        const deleteBtn = expertItem.querySelector('.delete-expert-btn');
        if (deleteBtn) {
          deleteBtn.addEventListener('click', () => {
            // 实际开发中这里应替换为真实的删除请求逻辑
            // console.log(`准备删除专家: ${expert.user_name}, ID: ${expert.user_id || '未知'}`);
            //确认弹框
            showConfirmModal(`确定要删除专家: ${expert.user_name}吗？`, function () {
              //实际开发中这里应替换为真实的删除请求逻辑
              request('api/ApiUser/deleteExpert', 'POST', {
                user_id: expert.user_id,
              }).then(data => {
                if (data.code === 1) {
                  showMessage('删除成功', 'success');
                  //刷新专家列表
                  initExpertList();
                } else {
                  showMessage(data.msg, 'error');
                }
              }).catch(error => {
                console.error('删除专家失败:', error);
              });
            });

          });
        }

        expertListContainer.appendChild(expertItem);
      });
    }
  }).catch(error => {
    console.error('获取专家列表失败:', error);
  });
}

function updateAdminUser() {
  const adminId = document.getElementById('edit-admin-id').value;
  const username = document.getElementById('edit-admin-username').value;
  const password = document.getElementById('edit-admin-password').value;
  const ssoId = document.getElementById('edit-admin-ssoId').value;
  request('api/ApiUser/updateAdmin', 'POST', {
    user_id: adminId,
    user_name: username,
    password: password,
    user_type: 1,
    ssoId: ssoId,
  }).then(data => {
    if (data.code === 1) {
      showMessage('更新成功', 'success');
      //关闭编辑管理员弹框
      closeEditAdminModal();
      //刷新管理员列表
      initAdminDataFun();
    } else {
      showMessage(data.msg, 'error');
    }
  }).catch(error => {
    console.error('更新管理员失败:', error);
  });
}

function updateExpertUser() {
  const expertId = document.getElementById('edit-expert-id').value;
  const username = document.getElementById('edit-expert-username').value;
  const password = document.getElementById('edit-expert-password').value;
  const ssoId = document.getElementById('edit-expert-ssoId').value;
  request('api/ApiUser/updateExpert', 'POST', {
    user_id: expertId,
    user_name: username,
    password: password,
    user_type: 2,
    ssoId: ssoId,
  }).then(data => {
    if (data.code === 1) {
      showMessage('更新成功', 'success');
      //关闭编辑专家弹框
      closeEditExpertModal();
      //刷新专家列表
      initExpertList();
    } else {
      showMessage(data.msg, 'error');
    }
  }).catch(error => {
    console.error('更新专家失败:', error);
  });
}

function closeEditAdminModal() {
  // 清空管理员信息字段
  document.getElementById('edit-admin-id').value = '';
  document.getElementById('edit-admin-username').value = '';
  document.getElementById('edit-admin-password').value = '';
  document.getElementById('edit-admin-ssoId').value = '';

  // 隐藏弹框
  document.getElementById('edit-admin-modal').style.display = 'none';
}

function openEditAdminModal(admin) {
  // 填充管理员信息到弹框中
  document.getElementById('edit-admin-id').value = admin.user_id;
  document.getElementById('edit-admin-username').value = admin.user_name;
  document.getElementById('edit-admin-password').value = ''; // 密码字段通常不显示原始值
  document.getElementById('edit-admin-ssoId').value = admin.ssoId || '';

  // 显示弹框
  document.getElementById('edit-admin-modal').style.display = '';
}

function initAdminDataFun() {
  request('api/ApiUser/getExpertList', 'POST', { type: 1 }).then(data => {
    if (data.code === 1) {
      // 根据id expert-list 组装专家列表包括头像 昵称 添加日期
      const adminList = data.data;
      const adminListContainer = document.getElementById('admin-list');
      adminListContainer.innerHTML = '';
      adminList.forEach(admin => {
        const adminItem = document.createElement('div');
        adminItem.className = 'admin-item';
        // 设置管理员项样式，添加边距、边框、圆角和阴影效果
        adminItem.style.display = 'flex';
        adminItem.style.alignItems = 'center';
        adminItem.style.padding = '12px 16px';
        adminItem.style.marginBottom = '10px';
        adminItem.style.border = '1px solid #e0e0e0';
        adminItem.style.borderRadius = '6px';
        adminItem.style.backgroundColor = '#fff';
        adminItem.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.1)';
        adminItem.style.transition = 'all 0.3s ease';
        adminItem.onmouseenter = () => {
          adminItem.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.15)';
        };
        adminItem.onmouseleave = () => {
          adminItem.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.1)';
        };

        adminItem.innerHTML = `
          <img src="${admin.avatar ? baseUrl + admin.avatar : 'default_avatar.png'}" alt="${admin.user_name}" style="
            width: 48px;
            height: 48px;
            border-radius: 50%;
            margin-right: 16px;
            object-fit: cover;
          ">
          <div style="flex: 1;">
            <p style="margin: 0 0 4px 0; font-size: 16px; font-weight: bold; color: #333;">${admin.user_name}</p>
            <p style="margin: 0; font-size: 14px; color: #666;">${admin.create_time}</p>
          </div>

          <button class="edit-admin-btn" style="
            padding: 6px 12px;
            margin-right: 8px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
          ">编辑</button>

          <button class="delete-admin-btn" style="
            padding: 6px 12px;
            background-color: #ff4444;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
          ">删除</button>
        `;
        // 绑定编辑按钮点击事件
        const editBtn = adminItem.querySelector('.edit-admin-btn');
        if (editBtn) {
          editBtn.addEventListener('click', () => {
            // 打开编辑管理员弹框并填充数据
            openEditAdminModal(admin);
          });
        }
        // 绑定删除按钮点击事件
        const deleteBtn = adminItem.querySelector('.delete-admin-btn');
        if (deleteBtn) {
          deleteBtn.addEventListener('click', () => {
            //至少保留一个管理员
            if (adminList.length === 1) {
              showMessage('至少保留一个管理员', 'error');
              return;
            }

            showConfirmModal(`确定要删除管理员: ${admin.user_name}吗？`, function () {
              //实际开发中这里应替换为真实的删除请求逻辑
              request('api/ApiUser/deleteExpert', 'POST', {
                user_id: admin.user_id,
              }).then(data => {
                if (data.code === 1) {
                  showMessage('删除成功', 'success');
                  //刷新专家列表
                  initExpertList();
                } else {
                  showMessage(data.msg, 'error');
                }
              }).catch(error => {
                console.error('删除管理员失败:', error);
              });
            });

          });
        }
        adminListContainer.appendChild(adminItem);
      });
    }
  }).catch(error => {
    console.error('获取专家列表失败:', error);
  });
}

//初始化专家列表
function initExpertList() {
  initExpertDataFun();
  initAdminDataFun();
}

//封装公共请求
// function ssoRequest(url, method = 'GET', data = {}) {
//   return new Promise((resolve, reject) => {
//     const xhr = new XMLHttpRequest();
//     xhr.open(method, url, true);
//     xhr.setRequestHeader('Content-Type', 'application/json');
//     //设置请求超时时间30分钟
//     xhr.timeout = 5 * 6 * 1000; // 30 分钟超时
//     xhr.onreadystatechange = function () {
//       if (xhr.readyState === 4) {
//         if (xhr.status === 200) {
//           try {
//             const res = JSON.parse(xhr.responseText);
//             resolve(res);
//           } catch (e) {
//             reject(new Error('响应解析失败：' + e.message));
//           }
//         } else {
//           reject(new Error('请求失败，状态码：' + xhr.status));
//         }
//       }
//     };
//     xhr.onerror = function () {
//       reject(new Error('网络错误，请求未能发出'));
//     };
//     xhr.ontimeout = function () {
//       reject(new Error('请求超时'));
//     };
//     xhr.send(JSON.stringify(data));
//   });
// }

//封装公共请求
function request(url, method = 'GET', data = {}) {

  return new Promise((resolve, reject) => {
    //判断是否登录除了登录页面 
    if (url != 'api/ApiUser/userLogin' && url != 'api/ApiUser/userSsoLogin' && url != 'api/ApiUser/thirdSsoLogin') {
      const token = localStorage.getItem('token');
      if (!token) {
        showMessage('请先登录', 'error');
        window.location.href = ssoUrl ? ssoUrl : 'login.html';
        return;
      }
    }

    const xhr = new XMLHttpRequest();
    xhr.open(method, baseUrl + url, true);
    xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
    xhr.setRequestHeader('method', 'tkh5');
    xhr.setRequestHeader('token', localStorage.getItem('token'));
    xhr.onreadystatechange = function () {

      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          resolve(JSON.parse(xhr.responseText));
        } else {
          if (xhr.status === 401) {
            showMessage('登录过期，请重新登录', 'error');
            window.location.href = ssoUrl ? ssoUrl : 'login.html';
            return;
          }
          reject(new Error('请求失败，状态码：' + xhr.status));
        }
        // checkSsoLogin();
      }
    };
    xhr.send(JSON.stringify(data));
  });

}

//查找最后一次模型配置
function getLastModelConfig() {
  request('api/Analysis/getLastModelConfig', 'POST', {}).then(data => {
    if (data.code === 1) {
      initModelConfig(data.data);//初始化大模型配置
      initSourceData(data.data);//初始化数据源
      initPromptFramework(data.data);//初始化提示词框架
    }
  }).catch(error => {
    console.error('获取模型配置失败:', error);
  });
}

//初始化提示词框架
function initPromptFramework(configResult = {}) {
  //关键词模板
  request('api/Analysis/getKeywordTemplateList', 'POST', {}).then(data => {
    if (data.code === 1) {
      initKeywordTemplatePage(data.data, configResult.keyword_template_id);
    }
  }).catch(error => {
    console.error('获取数据源列表失败:', error);
  });
}

//初始化数据源
function initSourceData(configResult = {}) {
  //数据源列表
  request('api/DataBase/getDataSourceList', 'POST', {}).then(data => {
    if (data.code === 1) {
      initAnalysisPage(data.data.dataSourceList, configResult.data_source);
    }
  }).catch(error => {
    console.error('获取数据源列表失败:', error);
  });
}

//初始化大模型配置
function initModelConfig(configResult = {}) {
  const modelSelect = document.getElementById('model-select');
  const modalData = [
    { model_name: 'DeepSeek' },
    { model_name: '通义千问' },
    { model_name: '文心一言' },
    { model_name: '混元' },
  ];
  //清空选项
  modelSelect.innerHTML = '';
  //添加选项
  modalData.forEach(item => {
    const option = document.createElement('option');
    option.value = item.model_name;
    if (item.model_name === configResult.model_name) {
      option.selected = true;
    }
    option.textContent = item.model_name;
    modelSelect.appendChild(option);
  })
  //初始化温度配置
  const temperatureInput = document.getElementById('temperature-input');
  const temperatureValue = document.getElementById('temperature-value');
  temperatureInput.value = configResult.model_temperature;
  temperatureValue.textContent = configResult.model_temperature;
}


//分析模块源数据选择
function initAnalysisPage(datasource, defaultsource = "") {
  // 将 defaultsource 字符串按逗号分割成数组
  const defaultSourceArray = defaultsource.split(',').map(item => item.trim());
  //动态渲染
  let datasourceHtml = '';
  datasource.forEach(item => {
    //判断是否默认选中
    let isChecked = defaultSourceArray.includes(item.id.toString());
    datasourceHtml += `
                        <div class="list-item datasource-list-list-item">
                          <div>
                              <div class="list-title">${item.name}</div>
                          </div>
                          <div>
                              <input type="checkbox" class="datasource-checkbox" value="${item.id}" ${isChecked ? 'checked' : ''}>
                          </div>
                      </div>
                      <!-- 期刊论文数据库示例 -->
                      <div class="data-example" style="margin: 10px 0; padding: 10px; background-color: #f5f5f5; border-radius: 4px; display: none;" id="journal-example">
                          <div style="font-size: 12px;">
                              <strong>示例数据：</strong><br>
                              测试数据
                              <br><br>
                              <strong>关键属性：</strong><br>
                              • 测试数据<br> 
                          </div>
                      </div>
                      `;
  });
  //将html插入到页面中
  document.getElementById('datasource-list').innerHTML = datasourceHtml;
  // 绑定数据源选择事件
  bindDatasourceSelectEvents();
}
// 绑定数据源选择事件
function bindDatasourceSelectEvents() {
  const datasourceItems = document.querySelectorAll('.datasource-list-list-item');
  datasourceItems.forEach(item => {
    // 获取当前项中的复选框
    const checkbox = item.querySelector('input[type="checkbox"]');
    if (checkbox) {
      checkbox.addEventListener('change', function () {
        item.classList.toggle('selected', this.checked);
        const example = item.nextElementSibling;
        if (example) {
          example.style.display = this.checked ? 'block' : 'none';
        }
      });
    }
  });
}

//初始化任务列表
function initTaskListPage(taskList = []) {
  let taskListHtml = '';
  taskList.forEach(item => {
    taskListHtml += `
        <div class="list-item">
            <div>
                <div class="list-title">任务#${item.no}</div> 
                ${item.state === 1 ?
        `<div class="list-meta">状态:已提交到大模型 | 进度: ${item.progress || '0'}%</div>`
        : item.state === 2 ?
          `<div class="list-meta">状态:大模型分析完成 | 完成时间: ${item.complete_time || ''}</div>`
          : ''
      }
                </div>
            <div>
                ${item.state === 1 ? `<button class="btn btn-sm btn-secondary progress-sync-btn" data-task="${item.id}">同步大模型分析结果</button>` : ''}
                <button class="btn btn-sm btn-secondary progress-detail-btn" data-task="${item.id}">查看详情</button>
            </div>
        </div>
    `;
  });
  //将html插入到页面中
  document.getElementById('tab-progress').innerHTML = taskListHtml;
  // 绑定详情按钮点击事件
  bindProgressDetailBtnClick();

}
// 绑定详情按钮点击事件
function bindProgressDetailBtnClick() {
  const detailButtons = document.querySelectorAll('.progress-detail-btn');
  detailButtons.forEach(button => {
    button.addEventListener('click', function () {
      const taskId = this.dataset.task;
      // 跳转到任务详情页
      window.location.href = `task-results.html?id=${taskId}`;
    });
  });


  const syncButtons = document.querySelectorAll('.progress-sync-btn');
  syncButtons.forEach(button => {
    button.addEventListener('click', function () {
      const taskId = this.dataset.task;
      // 发送同步请求
      request('api/Task/syncModalRst', 'POST', { id: taskId }).then(data => {
        if (data.code === 1) {
          // 同步成功，刷新任务列表
          getTaskList();
        } else {
          // 同步失败，提示用户
          showMessage('同步失败，请稍后重试');
        }
      }).catch(error => {
        console.error('同步大模型分析结果失败:', error);
        // 同步失败，提示用户
        showMessage('同步失败，请稍后重试');
      });
    });
  });
}

//获取任务列表
function getTaskList() {
  request('api/Task/getTaskList', 'POST', {}).then(data => {
    if (data.code === 1) {
      initTaskListPage(data.data.taskList);
    }
  }).catch(error => {
    console.error('获取任务列表失败:', error);
  });
}


// 初始化应用
function initApp() {
  // 下拉菜单交互
  const dropdownButtons = document.querySelectorAll('.dropdown-btn');
  dropdownButtons.forEach(button => {
    button.addEventListener('click', function (e) {
      e.preventDefault();
      const dropdown = this.closest('.navbar-dropdown');
      const menu = dropdown.querySelector('.dropdown-menu');
      // 切换当前下拉菜单
      menu.classList.toggle('show');
      // 关闭其他下拉菜单
      document.querySelectorAll('.navbar-dropdown').forEach(item => {
        if (item !== dropdown) {
          item.querySelector('.dropdown-menu').classList.remove('show');
        }
      });
    });
  });
  // 点击页面其他地方关闭下拉菜单
  document.addEventListener('click', function (e) {
    if (!e.target.closest('.navbar-dropdown')) {
      document.querySelectorAll('.dropdown-menu').forEach(menu => {
        menu.classList.remove('show');
      });
    }
  });


  const currentPage = document.body.dataset.page;

  // 检查当前页面是否不是登录页面，若不是则执行后续逻辑
  if (window.location.href.indexOf('login.html') === -1 && currentPage != 'settings') {
    if (localStorage.getItem('user_type') != 1 && currentPage != 'evaluation') {
      window.location.assign('evaluation.html');
    }
  }

  switch (currentPage) {
    case 'home':

      initHomePage();
      break;
    case 'themes':
      request('api/Analysis/getThemeList', 'POST', {}).then(data => {
        if (data.code === 1) {
          initThemesPage(data.data);
        }
      }).catch(error => {
        console.error('获取主题列表失败:', error);
      });
      //查找最后一次模型配置
      getLastModelConfig();
      //获取任务列表
      getTaskList();

      break;
    case 'evaluation':
      initEvaluationPage();
      break;
    case 'data':
      //数据源列表
      request('api/DataBase/getDataSourceList', 'POST', {}).then(data => {
        if (data.code === 1) {
          initDataPage(data.data);
          //总数据量
          document.getElementById('total-data-count').textContent = data.data.total;
          //今日新增
          document.getElementById('today-add-count').textContent = data.data.todayAdd;
        }
      }).catch(error => {
        console.error('获取数据源列表失败:', error);
      });
      break;
    case 'settings':
      initSettingsPage();
      initExpertList();
      initUserInfo();

      let userType = localStorage.getItem('user_type');
      if (userType == 2) {
        document.getElementById('expert-card').style.display = 'none';
        document.getElementById('admin-card').style.display = 'none';
      }
      break;
    case 'task-results':
      initTaskResultsPageData();
      break;
  }
}

// 关闭专家数量输入模态框
function closeExpertCountModal() {
  document.getElementById('expertCountModal').style.display = 'none';
}

// 绑定通用事件
function bindCommonEvents() {
  // 移动端菜单切换
  const menuToggle = document.querySelector('.menu-toggle');
  if (menuToggle) {
    menuToggle.addEventListener('click', toggleMenu);
  }

  // 返回按钮
  const backButtons = document.querySelectorAll('.btn-back');
  backButtons.forEach(button => {
    button.addEventListener('click', goBack);
  });

  // 表单提交
  const forms = document.querySelectorAll('form');
  forms.forEach(form => {
    form.addEventListener('submit', handleFormSubmit);
  });

  // 查看评估按钮事件监听器
  // const evaluationButtons = document.querySelectorAll('.evaluation-btn');
  // evaluationButtons.forEach(button => {
  //   button.addEventListener('click', function () {
  //     debugger
  //     const themeName = this.dataset.theme;
  //     showEvaluationDetailModal(themeName);
  //   });
  // });

  // 评估详情按钮事件监听器
  const detailButtons = document.querySelectorAll('.detail-btn');
  detailButtons.forEach(button => {
    button.addEventListener('click', function () {
      const themeName = this.dataset.theme;
      showEvaluationDetailModal(themeName);
    });
  });

  // 绑定查看评估详情模态框关闭事件
  const closeEvaluationDetailModal = document.getElementById('close-evaluation-detail-modal');
  if (closeEvaluationDetailModal) {
    closeEvaluationDetailModal.addEventListener('click', function () {
      document.getElementById('evaluation-detail-modal').style.display = 'none';
    });
  }

  // 点击查看评估详情模态框背景关闭
  const evaluationDetailModal = document.getElementById('evaluation-detail-modal');
  if (evaluationDetailModal) {
    evaluationDetailModal.addEventListener('click', function (event) {
      if (event.target === evaluationDetailModal) {
        evaluationDetailModal.style.display = 'none';
      }
    });
  }
}

// 切换菜单显示状态
function toggleMenu() {
  const menu = document.querySelector('.side-menu');
  if (menu) {
    menu.classList.toggle('open');
  }
}

//判断user_type  
const userType = localStorage.getItem('user_type');
if (userType == 2) {
  // 只显示评估菜单
  const evaluationMenu = document.querySelector('.nav-item');
  //隐藏前三个
  const navItems = evaluationMenu.parentElement.children;
  for (let i = 0; i < 3; i++) {
    navItems[i].style.display = 'none';
  }
}

// 返回上一页
function goBack() {
  window.history.back();
}

// 处理表单提交
function handleFormSubmit(event) {
  // 阻止默认提交行为
  event.preventDefault();

  const form = event.target;
  const submitButton = form.querySelector('button[type="submit"]');

  //获取用户名和密码
  const userName = form.querySelector('input[name="user_name"]').value;
  const password = form.querySelector('input[name="password"]').value;
  // 校验用户名和密码是否为空
  if (!userName || !password) {
    showMessage('用户名和密码不能为空', 'error');
    return;
  }
  // 显示加载状态
  if (submitButton) {
    submitButton.disabled = true;
    submitButton.innerHTML = '<span class="spinner"></span> 处理中...';
  }
  request('api/ApiUser/userLogin', 'POST', {
    user_name: userName,
    password: password
  }).then(data => {
    if (data.code === 1) {
      // 登录成功，保存token 
      localStorage.setItem('token', data.data.token);
      // 保存用户类型
      localStorage.setItem('user_type', data.data.user_type);
      localStorage.setItem('user_name', data.data.user_name);
      localStorage.setItem('user_avatar', data.data.user_avatar);

      //如果是普通用户跳转评估页面
      if (data.data.user_type == 2) {
        window.location.assign('evaluation.html');
      } else {
        // 跳转到首页
        window.location.href = 'index.html';
      }


    } else {
      submitButton.disabled = false;
      submitButton.innerHTML = '提交';
      showMessage(data.msg, 'error');
      // 登录失败，清空token
      localStorage.removeItem('token');
    }
  }).catch(error => {
    submitButton.disabled = false;
    submitButton.innerHTML = '提交';
    showMessage('登录失败', 'error');
  });



  // 模拟表单提交处理
  // setTimeout(() => {
  //   // 恢复按钮状态
  //   if (submitButton) {
  //     submitButton.disabled = false;
  //     submitButton.innerHTML = '提交';
  //   }

  //   // 显示成功消息
  //   showMessage('操作成功', 'success');
  // }, 1000);
}

//再创建一个消息提示用弹框的形式
function showMessage(message, type = 'info') {
  // 创建消息元素
  const alert = document.createElement('div');
  alert.className = `alert alert-${type}`;
  alert.textContent = message;

  // 设置弹出样式，调整 top 值使弹框位置靠页面上面部分
  alert.style.position = 'fixed';
  alert.style.top = '20%';
  alert.style.left = '50%';
  alert.style.transform = 'translate(-50%, -50%)';
  alert.style.padding = '15px 20px';
  alert.style.borderRadius = '4px';
  alert.style.zIndex = '9999';
  alert.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';

  // 添加到 body
  document.body.appendChild(alert);

  // 3秒后自动移除
  setTimeout(() => {
    alert.remove();
  }, 3000);
}


// 显示消息提示
function showMessagebk(message, type = 'info') {
  // 创建消息元素
  const alert = document.createElement('div');
  alert.className = `alert alert-${type}`;
  alert.textContent = message;

  // 插入到页面顶部
  const container = document.querySelector('.main-content .container');
  if (container) {
    container.insertBefore(alert, container.firstChild);

    // 3秒后自动移除
    setTimeout(() => {
      alert.remove();
    }, 3000);
  }
}

// 首页初始化
function initHomePage() {

  request('api/Task/getLatestTechPoint', 'POST', {}).then(data => {
    if (data.code === 1) {
      let techPointList = data.data;

      let latestTechPointList = document.getElementById('latest-tech-point-list');
      if (latestTechPointList) {
        latestTechPointList.innerHTML = '';
      }
      techPointList.forEach(techPoint => {
        let listItem = document.createElement('div');
        listItem.className = 'list-item';
        listItem.innerHTML = `
          <div>
            <div class="list-title">${techPoint.tech_point_name}</div>
            <div class="list-meta">${techPoint.create_time}</div>
          </div>
          <div>
            <a href="task-results.html?id=${techPoint.task_id}" class="btn btn-sm btn-secondary">查看详情</a>
          </div>
        `;
        latestTechPointList.appendChild(listItem);
      });

    } else { }
  }).catch(error => { });
  // 模拟加载数据
  // loadDashboardData();
}

// 加载仪表板数据
function loadDashboardData() {
  // 显示加载状态
  const dashboardContainer = document.getElementById('dashboard-stats');
  if (dashboardContainer) {
    dashboardContainer.innerHTML = '<div class="loading"><div class="spinner"></div></div>';

    // 模拟数据加载
    setTimeout(() => {
      dashboardContainer.innerHTML = `
        <div class="row">
          <div class="col-6">
            <div class="card text-center">
              <div class="card-title">新增主题</div>
              <div class="mt-2"><strong>15</strong></div>
            </div>
          </div>
          <div class="col-6">
            <div class="card text-center">
              <div class="card-title">待审主题</div>
              <div class="mt-2"><strong>8</strong></div>
            </div>
          </div>
          <div class="col-6">
            <div class="card text-center">
              <div class="card-title">专家评估</div>
              <div class="mt-2"><strong>12</strong></div>
            </div>
          </div>
          <div class="col-6">
            <div class="card text-center">
              <div class="card-title">源数据</div>
              <div class="mt-2"><strong>5</strong></div>
            </div>
          </div>
        </div>
      `;
    }, 1000);
  }
}

// 主题识别页面初始化
function initThemesPage(themesData) {
  console.log('初始化主题识别页面');

  // 绑定筛选事件
  const filterForm = document.getElementById('theme-filter-form');
  if (filterForm) {
    filterForm.addEventListener('submit', filterThemes);
  }

  // 加载主题数据
  loadThemes(themesData);
}


//关键词模板页面初始化
function initKeywordTemplatePage(keywordTemplateList, selectedTemplateId = '') {
  //根据id prompt-category 动态渲染关键词模板
  const promptCategory = document.getElementById('prompt-category');
  if (promptCategory) {
    promptCategory.innerHTML = '';
  }
  //遍历关键词模板列表
  keywordTemplateList.forEach(item => {
    //option
    const option = document.createElement('option');
    option.value = item.id;

    option.textContent = item.name;
    promptCategory.appendChild(option);
  })
  //绑定选择事件
  promptCategory.addEventListener('change', function () {
    //获取选中的关键词模板
    const selectedPrompt = keywordTemplateList.find(item => item.id == this.value);
    if (selectedPrompt) {
      //更新提示词模板标题
      document.getElementById('prompt-category-label').textContent = selectedPrompt.name;
      //将选中的关键词模板内容填充到textarea中
      document.getElementById('prompt-content').value = selectedPrompt.data_demo;
      //显示提示词模板
      document.getElementById('theme-prompt').style.display = 'block';

    }
  })
  //默认选择第一个关键词模板
  if (promptCategory.options.length > 0) {
    //如果有选中的关键词模板id，默认选择该关键词模板
    if (selectedTemplateId) {
      promptCategory.value = selectedTemplateId;
    } else {
      //如果没有选中的关键词模板id，默认选择第一个关键词模板
      promptCategory.options[0].selected = true;
    }
  }
  //触发默认选择事件
  promptCategory.dispatchEvent(new Event('change'));
}

// 保存模型配置
function saveModelConfig() {
  const modelSelect = document.getElementById('model-select');
  const temperatureInput = document.getElementById('temperature-input');
  const temperatureValue = document.getElementById('temperature-value');
  const modelConfig = {
    model_name: modelSelect.value,
    model_temperature: temperatureInput.value,
  };
  // 发送请求保存配置
  request('api/Analysis/saveConfig', 'POST', modelConfig).then(data => {
    if (data.code === 1) {
      showMessage('保存成功');
    } else {
      showMessage('保存失败', 'error');
    }
  }).catch(error => {
    console.error('保存配置失败:', error);
    showMessage('保存失败', 'error');
  });
}

// 保存选中的源数据
function saveSelectedData() {
  //获取所有选中的源数据
  const selectedData = document.querySelectorAll('.datasource-checkbox:checked');
  const selectedDataArray = Array.from(selectedData).map(checkbox => checkbox.value);
  // 发送请求保存选中的源数据
  request('api/Analysis/saveConfig', 'POST', { data_source: selectedDataArray.join(',') }).then(data => {
    if (data.code === 1) {
      showMessage('保存成功');
    } else {
      showMessage('保存失败', 'error');
    }
  }).catch(error => {
    console.error('保存选中的源数据失败:', error);
    showMessage('保存失败', 'error');
  });
}


// 加载主题数据
function loadThemes(themesData) {
  let themeList = themesData.themeList;//技术主题列表
  // 显示加载状态
  const themesContainer = document.querySelector('.tree-view');
  if (themesContainer) {
    let treeHtml = '';
    themeList.forEach(theme => {
      treeHtml += `
    <div class="tree-item" style="margin-top:10px !important">
      <div class="tree-header">
        <span>${theme.name}</span>
        
      </div>
      ${theme.children ? `<div class="tree-children">${generateTreeChildren(theme.children)}</div>` : ''}
    </div>
  `;
    });
    themesContainer.innerHTML = treeHtml;
    // 绑定树形结构展开/折叠事件
    bindTreeToggleEvents();


  }
}
// 树形结构展开/折叠 事件绑定
function bindTreeToggleEvents() {
  const treeHeaders = document.querySelectorAll('.tree-header');
  treeHeaders.forEach(header => {
    header.addEventListener('click', function () {
      this.classList.toggle('expanded');
      const children = this.nextElementSibling;
      if (children) {
        children.classList.toggle('expanded');
      }
    });
  });

  //绑定技术主题查看详情按钮事件
  const evaluationDetailButtons = document.querySelectorAll('.evaluation-detail-btn');
  evaluationDetailButtons.forEach(button => {
    button.addEventListener('click', function () {
      const themeName = this.dataset.theme;
      const themeId = this.dataset.id; 
      //根据主题id 查找最后一个任务
      request('api/Analysis/getLastTaskByThemeId', 'POST', { theme_id: themeId }).then(data => {
        if (data.code === 1) {
          if (data.data) {
            showEvaluationDetailModal(themeName, data.data.id,2);
          } else {
            showMessage('暂无评估数据', 'error');
          }
        } else {
          showMessage('获取失败', 'error');
        }
      }).catch(error => {
        console.error('获取最后一个任务失败:', error);
        showMessage('获取失败', 'error');
      });
    });
  });
 

  // 绑定技术主题查看评估按钮事件
  const evaluationButtons = document.querySelectorAll('.evaluation-btn');
  evaluationButtons.forEach(button => {
    button.addEventListener('click', function () {
      const themeName = this.dataset.theme;
      const themeId = this.dataset.id;
      //根据主题id 查找最后一个任务
      request('api/Analysis/getLastTaskByThemeId', 'POST', { theme_id: themeId }).then(data => {
        if (data.code === 1) {
          if (data.data) {
            showEvaluationDetailModal(themeName, data.data.id, 1);
          } else {
            showMessage('暂无评估数据', 'error');
          }
        } else {
          showMessage('获取失败', 'error');
        }
      }).catch(error => {
        console.error('获取最后一个任务失败:', error);
        showMessage('获取失败', 'error');
      });
    });
  });

  // 绑定技术主题查看详情按钮事件
  const detailButtons = document.querySelectorAll('.detail-btn');
  detailButtons.forEach(button => {
    button.addEventListener('click', function () {
      const themeName = this.dataset.theme;
      showThemeDetail(themeName);
    });
  });
}
function generateTreeChildren(children) {
  let childrenHtml = '';
  children.forEach(child => {
    if (child.children.length > 0) {
      childrenHtml += `
        <div class="tree-item" style='margin-top:10px !important'>
          <div class="tree-header">
            <span>${child.name}</span>
            <div class="evaluation-actions">
              <button class="btn btn-sm btn-secondary evaluation-btn" data-id="${child.id}" data-theme="${child.name}">查看评估</button>
              <button class="btn btn-sm btn-secondary evaluation-detail-btn" data-id="${child.id}" data-theme="${child.name}">查看详情</button>
            </div>
          </div>
          <div class="tree-children">
            ${generateTreeChildren(child.children)}
          </div>
        </div>
      `;
    } else {
      childrenHtml += `
        <div class="tree-leaf" style='margin:5px 0'>
          <span style='float:left'>${child.name}</span>
          <div class="evaluation-actions">
            <button class="btn btn-sm btn-secondary evaluation-btn" data-id="${child.id}" data-theme="${child.name}">查看评估</button>
            <button class="btn btn-sm btn-secondary evaluation-detail-btn" data-id="${child.id}" data-theme="${child.name}">查看详情</button>
          </div>
        </div>
      `;
    }
  });
  return childrenHtml;
}



// 筛选主题
function filterThemes(event) {
  event.preventDefault();
  showMessage('筛选条件已应用', 'success');
  loadThemes();
}


//待评估列表
function loadEvaluationList() {
  request('api/Evaluation/getEvaluationList', 'POST', {}).then(data => {
    if (data.code === 1) {
      let evaluationList = data.data;//待评估列表
      let evaluationListHtml = '';
      evaluationList.forEach(item => {
        evaluationListHtml += `
        <div class="list-item">
                    <div>
                        <div class="list-title">${item.tech_point_name}</div>
                        <div class="list-meta">截止时间: ---</div>
                    </div>
                    <div class="evaluation-actions"> 
                        <div class="show_evacode" style="${localStorage.getItem('user_type') === '1' ? '' : 'display: none;'}">评估码：${item.task.evaluation_code}</div>
                        <button style="${localStorage.getItem('user_type') === '2' ? '' : 'display: none;'}" class="btn btn-sm start-evaluation"   data-techpointid="${item.id}" data-theme="${item.tech_point_name}">开始评估</button>     
                    </div>
                </div>
                `;
      });



      document.getElementById('evaluation-list').innerHTML = evaluationListHtml;
      // 绑定开始评估按钮事件
      const startEvaluationButtons = document.querySelectorAll('.start-evaluation');
      startEvaluationButtons.forEach(button => {
        button.addEventListener('click', function () {
          const modelName = this.dataset.theme;
          const techpointid = this.dataset.techpointid;

          document.getElementById('evaluation-code-input').value = '';
          document.getElementById('evaluation-code-modal').style.display = 'block';
          document.getElementById('evaluation-theme').value = modelName;
          document.getElementById('evaluation-techpointid').value = techpointid;

          // showEvaluationModal(modelName, taskId);
        });
      });
    }
  }).catch(error => {
    console.error('获取待评估列表失败:', error);
  });
}

//初始化进行中的评估
function getOngoingAssessmentData() {
  request('api/Evaluation/getOngoingAssessmentList', 'POST', {}).then(data => {
    if (data.code === 1) {
      let ongoingAssessmentList = data.data;//进行中的评估列表
      let ongoingAssessmentListHtml = '';
      ongoingAssessmentList.forEach(item => {
        ongoingAssessmentListHtml += `
        <div class="list-item">
                    <div>
                        <div class="list-title">${item.tech_point_name}</div>
                        <div class="list-meta">已评估:技术重要性、技术成熟度</div>
                    </div>
                    <div class="evaluation-actions">
                        <button class="btn btn-sm btn-secondary continue-evaluation" data-techpointid="${item.id}" data-theme="${item.tech_point_name}">继续评估</button>
                    </div>
                </div>
                `;
      });
      document.getElementById('ongoing-assessment-list').innerHTML = ongoingAssessmentListHtml;
      // 绑定继续评估按钮事件
      const continueEvaluationButtons = document.querySelectorAll('.continue-evaluation');
      continueEvaluationButtons.forEach(button => {
        button.addEventListener('click', function () {
          const themeName = this.dataset.theme;
          const techpointid = this.dataset.techpointid;
          document.getElementById('evaluation-code-input').value = '';
          document.getElementById('evaluation-code-modal').style.display = 'block';
          document.getElementById('evaluation-theme').value = themeName;
          document.getElementById('evaluation-techpointid').value = techpointid;

        });
      });
    }
  }).catch(error => {
    console.error('获取待评估列表失败:', error);
  });
}

//提交评估码
function submitEvaluationCode() {
  const themeName = document.getElementById('evaluation-theme').value;
  const techpointid = document.getElementById('evaluation-techpointid').value;
  const evaluationCode = document.getElementById('evaluation-code-input').value;
  if (!evaluationCode) {
    showMessage('请输入评估码', 'error');
    return;
  }
  //验证评估码
  request('api/Evaluation/verifyEvaluationCode', 'POST', {
    evaluation_code: evaluationCode,
    tech_point_id: techpointid
  }).then(data => {
    if (data.code === 1) {
      let techPointDetail = data.data.techPointDetail;
      showEvaluationModal(themeName, techpointid, techPointDetail);
      closeEvaluationCodeModal();
    } else {
      showMessage('评估码验证失败', 'error');
      return;
    }
  }).catch(error => {
    console.error('评估码验证失败:', error);
  });


}


//关闭评估码弹窗
function closeEvaluationCodeModal() {
  document.getElementById('evaluation-code-modal').style.display = 'none';
}

//已评估列表
function loadEvaluatedList() {
  request('api/Evaluation/getAssessEvaluationList', 'POST', {}).then(data => {
    if (data.code === 1) {
      let evaluatedList = data.data;//已评估列表
      let evaluatedListHtml = '';
      evaluatedList.forEach(item => {
        evaluatedListHtml += `
        <div class="list-item">
                    <div>
                        <div class="list-title">${item.tech_point_name}</div>
                        <div class="list-meta">评估时间: ${item.create_time} | 专家: ${item.expert_name}</div>
                    </div>
                    <div class="evaluation-actions"> 
                        ${item.result == 0 ? `<button class="btn btn-sm btn-success adopt-btn" data-techpointid="${item.id}" data-theme="${item.tech_point_name}">采用</button>
                        <button class="btn btn-sm btn-secondary ignore-btn" data-techpointid="${item.id}" data-theme="${item.tech_point_name}">忽略</button>` : ''}
                        <button class="btn btn-sm btn-secondary detail-btn" data-techpointid="${item.id}" data-theme="${item.tech_point_name}">评估详情</button>
                    </div>
                </div>
                `;
      });
      document.getElementById('evaluated-list').innerHTML = evaluatedListHtml;
      // 绑定采用按钮事件
      const adoptButtons = document.querySelectorAll('.adopt-btn');
      adoptButtons.forEach(button => {
        button.addEventListener('click', function () {
          const themeName = this.dataset.theme;
          const techpointid = this.dataset.techpointid;
          // 使用自定义确认对话框
          showConfirmModal(`确定要采用"${themeName}"吗？确认之后该技术将加入技术目录中。`, function () {
            // showMessage(`已采用"${themeName}"`, 'success');
            // 这里可以添加将技术主题正式加入技术目录的逻辑 
            request('api/Evaluation/updateTask', 'POST', { tech_point_id: techpointid, result: 1 }).then(data => {
              if (data.code === 1) {
                let themeList = data.data.themeList || [];
                syncIdentify(themeList);
                showMessage(data.msg || '采用成功', 'success');
                loadEvaluatedList();
              } else {
                showMessage(data.msg || '采用失败', 'error');
              }
            }).catch(error => {
              showMessage(data.msg || '采用失败', 'error');
            });
          });
        });
      });

      // 绑定忽略按钮事件
      const ignoreButtons = document.querySelectorAll('.ignore-btn');
      ignoreButtons.forEach(button => {
        button.addEventListener('click', function () {
          const themeName = this.dataset.theme;
          const techpointid = this.dataset.techpointid;
          // 使用自定义确认对话框
          showConfirmModal(`确定要忽略"${themeName}"吗？确认之后该记录将被删除。`, function () {
            // showMessage(`已忽略"${themeName}"`, 'info');
            // 这里可以添加忽略技术点的逻辑
            request('api/Evaluation/updateTask', 'POST', { tech_point_id: techpointid, result: 2 }).then(data => {
              if (data.code === 1) {
                showMessage(data.msg || '忽略成功', 'success');
                loadEvaluatedList();
              } else {
                showMessage(data.msg || '忽略失败', 'error');
              }
            }).catch(error => {
              showMessage(data.msg || '忽略失败', 'error');
            });
            console.log(`忽略: ${themeName}`);
          });
        });
      });
      // 绑定评估详情按钮事件
      const detailButtons = document.querySelectorAll('.detail-btn');
      detailButtons.forEach(button => {
        button.addEventListener('click', function () {
          const themeName = this.dataset.theme;
          const techpointid = this.dataset.techpointid;
          showEvaluationDetailModal(themeName, techpointid);
        });
      });
    }
  }).catch(error => {
    console.error('获取待评估列表失败:', error);
  });
}


//评估统计
function getEvaluationStatistics() {
  request('api/Evaluation/getEvaluationStatistics', 'POST', {}).then(data => {
    if (data.code === 1) {
      //更新页面
      document.getElementById('totalOngoing').textContent = data.data.totalOngoing;
      document.getElementById('totalOngoingAssessment').textContent = data.data.totalOngoingAssessment;
      document.getElementById('totalAssess').textContent = data.data.totalAssess;

    } else {
      showMessage(data.msg || '获取失败', 'error');
    }
  });
}

// 专家评估页面初始化
function initEvaluationPage() {
  console.log('初始化专家评估页面');
  loadEvaluationList();//待评估列表
  getOngoingAssessmentData();//进行中的评估列表
  loadEvaluatedList();//已评估列表
  getEvaluationStatistics();//评估统计

  // 绑定评分事件
  const ratingInputs = document.querySelectorAll('input[type="radio"]');
  ratingInputs.forEach(input => {
    input.addEventListener('change', handleRatingChange);
  });

  // 绑定开始评估按钮事件
  // const startEvaluationButtons = document.querySelectorAll('.start-evaluation');
  // startEvaluationButtons.forEach(button => {
  //   button.addEventListener('click', function () {
  //     debugger
  //     const themeName = this.dataset.theme;
  //     const techPointName = this.dataset.techPoint;
  //     if (themeName) {
  //       showEvaluationModal(themeName);
  //     } else if (techPointName) {
  //       showEvaluationModal(techPointName);
  //     }
  //   });
  // });

  // 绑定继续评估按钮事件
  // const continueEvaluationButtons = document.querySelectorAll('.continue-evaluation');
  // continueEvaluationButtons.forEach(button => {
  //   button.addEventListener('click', function () {
  //     const themeName = this.dataset.theme;
  //     showEvaluationModal(themeName);
  //   });
  // });

  // 绑定评估模态框关闭事件
  const closeEvaluationModal = document.getElementById('close-evaluation-modal');
  if (closeEvaluationModal) {
    closeEvaluationModal.addEventListener('click', function () {
      document.getElementById('evaluation-modal').style.display = 'none';
    });
  }

  // 绑定提交评估按钮事件
  const submitEvaluationButton = document.getElementById('submit-evaluation');
  if (submitEvaluationButton) {
    submitEvaluationButton.addEventListener('click', submitEvaluation);
  }

  // 绑定加入技术主题按钮事件
  const addToThemeButton = document.getElementById('add-to-theme');
  if (addToThemeButton) {
    addToThemeButton.addEventListener('click', addToTheme);
  }

  // 绑定忽略按钮事件
  const ignoreButton = document.getElementById('ignore-theme');
  if (ignoreButton) {
    ignoreButton.addEventListener('click', ignoreTheme);
  }

  // 点击评估模态框背景关闭
  const evaluationModal = document.getElementById('evaluation-modal');
  if (evaluationModal) {
    evaluationModal.addEventListener('click', function (event) {
      if (event.target === evaluationModal) {
        evaluationModal.style.display = 'none';
      }
    });
  }

  // 检查URL参数，如果是从任务结果页面跳转过来的，直接显示评估模态框
  const urlParams = new URLSearchParams(window.location.search);
  const techPoint = urlParams.get('techPoint');
  const theme = urlParams.get('theme');

  if (techPoint || theme) {
    const title = techPoint || theme;
    showEvaluationModal(title);
  }

  let userType = localStorage.getItem('user_type');
  if (userType == 2) {
    document.getElementById('evaluated-assessment-list').style.display = 'none';
    // document.getElementById('expert-card').style.display = 'none'; 
  }
  // 绑定已完成评估的"采用"和"忽略"按钮事件
  // bindAdoptIgnoreButtons();
}

// 绑定已完成评估的"采用"和"忽略"按钮事件
// function bindAdoptIgnoreButtons() {
//   // 绑定采用按钮事件
//   const adoptButtons = document.querySelectorAll('.adopt-btn');
//   adoptButtons.forEach(button => {
//     button.addEventListener('click', function () {
//       const themeName = this.dataset.theme;
//       // 使用自定义确认对话框
//       showConfirmModal(`确定要采用"${themeName}"吗？确认之后该技术将加入技术目录中。`, function () {
//         showMessage(`已采用"${themeName}"`, 'success');
//         // 这里可以添加将技术主题正式加入技术目录的逻辑
//         console.log(`采用: ${themeName}`);
//       });
//     });
//   });

//   // 绑定忽略按钮事件
//   const ignoreButtons = document.querySelectorAll('.ignore-btn');
//   ignoreButtons.forEach(button => {
//     button.addEventListener('click', function () {
//       const themeName = this.dataset.theme;
//       // 使用自定义确认对话框
//       showConfirmModal(`确定要忽略"${themeName}"吗？确认之后该记录将被删除。`, function () {
//         showMessage(`已忽略"${themeName}"`, 'info');
//         // 这里可以添加忽略技术点的逻辑
//         console.log(`忽略: ${themeName}`);
//       });
//     });
//   });
// }

// 关闭评估详情弹窗
function closeEvaluationDetailModal() {
  document.getElementById('evaluation-detail-modal').style.display = 'none';
}

// 显示自定义确认对话框
function showConfirmModal(message, onConfirm) {
  const confirmModal = document.getElementById('confirm-modal');
  const confirmMessage = document.getElementById('confirm-modal-message');
  const confirmButton = document.getElementById('confirm-modal-confirm');
  const cancelButton = document.getElementById('confirm-modal-cancel');

  // 设置确认消息
  confirmMessage.textContent = message;

  // 绑定确认按钮事件
  confirmButton.onclick = function () {
    confirmModal.style.display = 'none';
    if (onConfirm) onConfirm();
  };

  // 绑定取消按钮事件
  cancelButton.onclick = function () {
    confirmModal.style.display = 'none';
  };

  // 点击背景关闭
  confirmModal.onclick = function (event) {
    if (event.target === confirmModal) {
      confirmModal.style.display = 'none';
    }
  };

  // 显示模态框
  confirmModal.style.display = 'flex';
}

// 处理评分变化
function handleRatingChange(event) {
  const input = event.target;
  const groupName = input.name;
  const value = input.value;

  console.log(`评分组 ${groupName} 选择值: ${value}`);
}


// 显示评估模态框
function showEvaluationModal(themeName, techpointid, techPointDetail = {}) {

  // 隐藏评估详情弹窗
  closeEvaluationDetailModal();
  // 设置评估任务ID
  document.getElementById('evaluation-techpointid_tj').value = techpointid;

  const modal = document.getElementById('evaluation-modal');
  const title = document.getElementById('evaluation-theme-title');

  if (techPointDetail) {
    document.getElementById('tech-point-title').textContent = techPointDetail.tech_point_name || '';
    document.getElementById('tech-point-directory').textContent = techPointDetail.first_theme_name + ' > ' + techPointDetail.second_theme_name;
    document.getElementById('tech-topic-title').textContent = techPointDetail.second_theme_name || '';
    document.getElementById('tech-topic-directory').textContent = techPointDetail.first_theme_name;
    let tech_development_prediction = techPointDetail.tech_development_prediction || '';
    tech_development_prediction = tech_development_prediction ? JSON.parse(tech_development_prediction) : {}

    const futurePointsContainer = document.getElementById('futurePointsContainer');
    // 清空之前的内容
    futurePointsContainer.innerHTML = '';
    var futureHtml = '';
    // 遍历预测数据，动态生成时间节点
    tech_development_prediction.developmentTrend.forEach(item => {
      const year = Object.keys(item)[0];//取对象的key值
      const year_num = Number(year.replace('years', ''));//years3 取数字 
      const trl = Object.values(item)[0];//取对象的value值 


      // 动态生成HTML
      futureHtml += `
      <div class="timeline-point  future-${year_num}y">
        <div class="point-marker"></div>
        <div class="point-label">${year_num}年后</div>
        <div class="point-value">TRL ${trl}</div>
      </div>
    `;

    });
    //在前面追加当前状态
    const currentState = tech_development_prediction.currentStatus;//当前状态 TRL 4 
    futureHtml = `
        <div class="timeline-point current">
          <div class="point-marker"></div>
          <div class="point-label">当前状态</div>
          <div class="point-value">TRL ${currentState}</div>
        </div>
      ` + futureHtml;
    // 插入到容器中
    futurePointsContainer.insertAdjacentHTML('beforeend', futureHtml);

  }
  // 设置主题名称
  title.textContent = themeName;
  // 清除之前的评分
  const ratingInputs = modal.querySelectorAll('input[type="radio"]');
  ratingInputs.forEach(input => {
    input.checked = false;
  });
  // 显示模态框
  modal.style.display = 'flex';
}

// 提交评估
function submitEvaluation() {

  // 获取所有评分
  const ratings = {};
  const ratingsComment = {};
  const ratingGroups = [
    'trl', 'performance', 'reliability', 'adoption', 'strategic',
    'strategic_value', 'urgency', 'risk', 'disruptive', 'synergy'
  ];

  ratingGroups.forEach(group => {
    const selected = document.querySelector(`input[name="${group}"]:checked`);
    if (selected) {
      ratings[group] = selected.value;
    }
  });

  // 获取所有评论
  const ratingCommentGroups = [
    'trl_comment', 'performance_comment', 'reliability_comment', 'adoption_comment', 'strategic_comment',
    'strategic_value_comment', 'urgency_comment', 'risk_comment', 'disruptive_comment', 'synergy_comment'
  ];
  // 获取所有评论
  ratingCommentGroups.forEach(group => {
    const comment = document.querySelector(`textarea[name="${group}"]`).value;
    if (comment) {
      ratingsComment[group] = comment;
    }
  });

  // 获取评估任务ID
  const techpointid = document.getElementById('evaluation-techpointid_tj').value;

  // 检查是否所有维度都已评分
  if (Object.keys(ratings).length < ratingGroups.length) {
    showMessage('请完成所有维度的评估', 'warning');
    return;
  }

  request('api/Evaluation/addEvaluation', 'POST', {
    techpointid: techpointid, ...ratings, ...ratingsComment
  }).then(data => {
    if (data.code === 1) {
      showMessage('评估提交成功', 'success');
      // 关闭模态框
      document.getElementById('evaluation-modal').style.display = 'none';
      //清空评分
      const ratingInputs = document.querySelectorAll('input[type="radio"]');
      ratingInputs.forEach(input => {
        input.checked = false;
      });
      //清空评论
      const commentInputs = document.querySelectorAll('textarea');
      commentInputs.forEach(input => {
        input.value = '';
      });
      //刷新页面
      location.reload();
    } else {
      showMessage(data.msg, 'error');

    }
  }).catch(error => {
    console.error('评估提交失败:', error);
    showMessage('评估提交失败', 'error');
  });


  // 显示提交成功消息
  // showMessage('评估提交成功', 'success');

  // 隐藏提交按钮，显示加入技术主题和忽略按钮
  // const submitButton = document.getElementById('submit-evaluation');
  // if (submitButton) {
  //   submitButton.style.display = 'none';
  // }

  // 显示加入技术主题和忽略按钮
  const actionButtons = document.getElementById('evaluation-action-buttons');
  if (actionButtons) {
    actionButtons.style.display = 'block';
  }

  // 这里可以添加将评估结果保存到服务器的代码
  console.log('评估结果:', ratings);
}

// 加入技术主题
function addToTheme() {
  const themeName = document.getElementById('evaluation-theme-title').textContent;
  showMessage(`已将"${themeName}"加入技术主题`, 'success');

  // 关闭模态框
  document.getElementById('evaluation-modal').style.display = 'none';

  // 这里可以添加将技术点加入技术目录的逻辑
  console.log(`将"${themeName}"加入技术主题`);
}

// 忽略技术主题
function ignoreTheme() {
  const themeName = document.getElementById('evaluation-theme-title').textContent;
  showMessage(`已忽略"${themeName}"`, 'info');

  // 关闭模态框
  document.getElementById('evaluation-modal').style.display = 'none';

  // 这里可以添加忽略技术点的逻辑
  console.log(`忽略"${themeName}"`);
}

// 显示评估详情模态框
// function showEvaluationDetailModal(themeName, taskId) {   
//   const modal = document.getElementById('evaluation-detail-modal');
//   if (modal) {
//     modal.style.display = 'block';
//     document.getElementById('evaluation-detail-modal-title').textContent = `评估详情: ${themeName}`;
//   }
// }

// 生成随机评估码
function generateEvaluationCode() {
  // 生成4位随机数字
  return Math.floor(1000 + Math.random() * 9000).toString();
}

// 初始化任务结果页面功能
function initTaskResultsPage() {
  console.log('初始化任务结果页面');
  // 绑定发起评估按钮事件
  // const startEvaluationButtons = document.querySelectorAll('.start-evaluation');
  // startEvaluationButtons.forEach(button => {
  //   button.addEventListener('click', function () { 
  //     const techPoint = this.dataset.techPoint;
  //     const theme = this.dataset.theme;

  //     // 跳转到评估页面并传递参数
  //     if (techPoint) {
  //       window.location.href = `evaluation.html?techPoint=${encodeURIComponent(techPoint)}`;
  //     } else if (theme) {
  //       window.location.href = `evaluation.html?theme=${encodeURIComponent(theme)}`;
  //     }
  //   });
  // });

  // 绑定116号任务记录的生成评估码按钮事件
  const generateCode116Button = document.getElementById('generateCode116');
  if (generateCode116Button) {
    generateCode116Button.addEventListener('click', function () {
      const evaluationCode = generateEvaluationCode();
      const codeDisplay = document.getElementById('evaluationCode116');
      if (codeDisplay) {
        codeDisplay.textContent = evaluationCode;
        showMessage('评估码已生成，请妥善保存', 'success');
      }
    });
  }

  // // 绑定117号任务记录的生成评估码按钮事件
  // const generateCode117Button = document.getElementById('generateCode117');
  // if (generateCode117Button) {
  //   generateCode117Button.addEventListener('click', function () {
  //     const evaluationCode = generateEvaluationCode();
  //     const codeDisplay = document.getElementById('evaluationCode117');
  //     if (codeDisplay) {
  //       codeDisplay.textContent = evaluationCode;
  //       showMessage('评估码已生成，请妥善保存', 'success');
  //     }
  //   });
  // }
}

// 数据管理页面初始化
function initDataPage(dataSourceList) {
  console.log('初始化源数据管理页面');
  // 渲染数据源列表
  renderDataSourceList(dataSourceList.dataSourceList);

  // 绑定源数据操作事件
  const dataSourceActions = document.querySelectorAll('.data-source-action');
  dataSourceActions.forEach(button => {
    button.addEventListener('click', handleDataSourceAction);
  });

  //渲染数据
  renderSelectDataSourceList(dataSourceList.dataSourceList);
  // 绑定源数据选择事件
  const dataSourceSelector = document.getElementById('data-source-selector');
  if (dataSourceSelector) {
    dataSourceSelector.addEventListener('change', function () {
      const selectedSource = this.value;
      if (selectedSource) {
        showDataExample(selectedSource, dataSourceList.dataSourceList);
      } else {
        // 隐藏源数据示例区域
        document.getElementById('data-example-container').style.display = 'none';
      }
    });
  }
}

// 渲染选中的数据源列表
function renderSelectDataSourceList(dataSourceList) {
  const dataSourceSelector = document.getElementById('data-source-selector');
  if (dataSourceSelector) {
    dataSourceSelector.innerHTML = '';
    // 添加默认选项
    const defaultOption = document.createElement('option');
    defaultOption.value = '';
    defaultOption.textContent = '请选择源数据';
    dataSourceSelector.appendChild(defaultOption);

    dataSourceList.forEach(dataSource => {
      const option = document.createElement('option');
      option.value = dataSource.id;
      option.textContent = dataSource.name;
      dataSourceSelector.appendChild(option);
    });
  }
}

// 渲染数据源列表
function renderDataSourceList(dataSourceList) {
  const parentList = document.querySelector('.data-source-list');
  if (parentList) {
    dataSourceList.forEach(dataSource => {
      let dataSourceItem = document.getElementById(`${dataSource.id}-item`);
      if (!dataSourceItem) {
        dataSourceItem = document.createElement('div');
        dataSourceItem.id = `${dataSource.id}-item`;
        dataSourceItem.classList.add('list-item');
        parentList.appendChild(dataSourceItem);
      }
      dataSourceItem.innerHTML = `
          <div>
            <div class="list-title">${dataSource.name}</div>
            <div class="list-meta">状态: 
            ${(() => {
          switch (dataSource.state) {
            case 1:
              return '更新中';
            case 2:
              return '正常运行';
            case 3:
              return '异常';
            default:
              return dataSource.status;
          }
        })()} | 更新时间: ${dataSource.update_time}</div>
          </div>
          <div>
            <button class="btn btn-sm btn-secondary data-source-action" data-action="refresh" data-source-id="${dataSource.id}">刷新</button>
          </div>
        `;
    });
  }
}

// 设置页面初始化
function initSettingsPage() {
  console.log('初始化设置页面');
}

// 绑定页签切换事件
function bindTabEvents() {
  const tabs = document.querySelectorAll('.tabs a');
  tabs.forEach(tab => {
    tab.addEventListener('click', function (event) {
      event.preventDefault();
      const target = this.getAttribute('href').substring(1);
      document.querySelectorAll('.tab-content').forEach(content => {
        content.style.display = 'none';
      });
      document.getElementById(target).style.display = 'block';
      tabs.forEach(t => t.classList.remove('active'));
      this.classList.add('active');
    });
  });
}

// 处理源数据操作
function handleDataSourceAction(event) {
  const button = event.target;
  const action = button.dataset.action;
  const sourceId = button.dataset.sourceId;

  switch (action) {
    case 'refresh':
      // 显示进度条
      showDataSourceProgress(sourceId, button);
      break;
    case 'delete':
      if (confirm('确认删除此源数据吗？')) {
        showMessage(`已删除源数据 ${sourceId}`, 'success');
      }
      break;
    default:
      showMessage('未知操作', 'warning');
  }
}

// 显示源数据刷新进度
function showDataSourceProgress(sourceId, button) {
  // 获取父级list-item元素
  const listItem = button.closest('.list-item');
  const originalContent = listItem.innerHTML;

  // 显示加载消息
  showMessage(`正在刷新源数据 ${sourceId}`, 'info');

  // 替换按钮为进度条
  const progressHtml = `
    <div class="data-source-progress" style="width: 100px;">
      <div class="progress-bar">
        <div id="progress-${sourceId}" style="width: 0%; height: 8px; background-color: #2E5A3E; border-radius: 4px;"></div>
      </div>
      <div class="text-center" id="progress-text-${sourceId}" style="font-size: 12px; margin-top: 4px;">0%</div>
    </div>
  `;

  // 替换按钮区域的内容
  const buttonContainer = button.parentElement;
  buttonContainer.innerHTML = progressHtml;

  // 模拟进度更新
  let progress = 0;
  const interval = setInterval(() => {
    progress += Math.floor(Math.random() * 10) + 1;
    if (progress >= 100) {
      progress = 100;
      clearInterval(interval);

      // 进度完成后的处理
      setTimeout(() => {
        // 恢复原始按钮
        buttonContainer.innerHTML = '';
        const newButton = document.createElement('button');
        newButton.className = sourceId === 'social' ? 'btn btn-sm btn-warning data-source-action' : 'btn btn-sm btn-secondary data-source-action';
        newButton.dataset.action = 'refresh';
        newButton.dataset.sourceId = sourceId;
        newButton.textContent = '刷新';
        newButton.addEventListener('click', handleDataSourceAction);
        buttonContainer.appendChild(newButton);

        // 更新状态文本
        const metaDiv = listItem.querySelector('.list-meta');
        if (metaDiv) {
          const now = new Date();
          const timeString = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
          metaDiv.innerHTML = `状态: 正常运行 | 更新时间: ${timeString}`;
        }

        showMessage(`源数据 ${sourceId} 刷新完成`, 'success');
      }, 500);
    }

    // 更新进度条显示
    const progressBar = document.getElementById(`progress-${sourceId}`);
    const progressText = document.getElementById(`progress-text-${sourceId}`);
    if (progressBar && progressText) {
      progressBar.style.width = `${progress}%`;
      progressText.textContent = `${progress}%`;
    }
  }, 200);
}

// 显示源数据示例
function showDataExample(sourceType, dataSourceList) {
  const demoData = dataSourceList.find(item => item.id == sourceType);
  if (!demoData) {
    showMessage('未找到该源数据的示例', 'warning');
    return;
  }

  const container = document.getElementById('data-example-container');
  const content = document.getElementById('data-example-content');
  // 显示加载状态
  content.innerHTML = '<div class="loading"><div class="spinner"></div></div>';
  container.style.display = 'block';
  content.innerHTML = generateDataExampleContent(demoData)
}

// 生成源数据示例内容
function generateDataExampleContent(demoData) {
  // let title, exampleData;
  let title = demoData.name;
  let exampleData = JSON.parse(demoData.data_demo);

  // switch (sourceType) {
  //   case 'journal':
  //     title = '期刊论文数据库示例';
  //     exampleData = {
  //       "A. 标识层": {
  //         "id": "uuid-00000001",
  //         "version": 1,
  //         "hash": "sha256-abcdef1234567890",
  //         "ingest_time": "2024-05-20T10:30:00Z",
  //         "pipeline_stage": "enriched"
  //       },
  //       "B. 来源与取数": {
  //         "source_type": "journal_article",
  //         "source_name": "国防科学技术",
  //         "source_link": "https://example.com/papers/爆震发动机应用研究",
  //         "fetch_method": "crawler",
  //         "license": "unknown",
  //         "retrieval_time": "2024-05-20T10:35:00Z",
  //         "provenance": {
  //           "agent": "crawler-agent-01",
  //           "batch_id": "batch-20240520-01",
  //           "data_center": "dc-beijing"
  //         }
  //       },
  //       "C. 内容层": {
  //         "language": "zh-CN",
  //         "title": "爆震发动机应用研究",
  //         "abstract": "本文研究了爆震发动机在军事后勤装备中的应用潜力，分析了其在提高运输效率和降低燃料消耗方面的优势。通过理论分析和实验验证，证明了爆震发动机在特定场景下的可行性。",
  //         "fulltext": "（完整论文文本内容）",
  //         "structure": {
  //           "sections": [
  //             { "heading": "引言", "text": "爆震发动机作为一种新型推进技术...", "page_range": "1-2" },
  //             { "heading": "技术原理", "text": "爆震发动机的工作原理基于...", "page_range": "2-5" }
  //           ],
  //           "tables": [],
  //           "figures": [],
  //           "references": [
  //             { "raw": "[1] 张三. 爆震发动机技术发展综述[J]. 航空学报, 2023." }
  //           ]
  //         },
  //         "attachments": [],
  //         "page_count": 10,
  //         "word_count": 8500
  //       },
  //       "D. 结构化抽取层": {
  //         "entities": {
  //           "equipments": [
  //             { "name": "爆震发动机", "normalized": "Pulse Detonation Engine", "offsets": [0, 4], "confidence": 0.95 }
  //           ],
  //           "methods": [
  //             { "name": "理论分析", "normalized": "Theoretical Analysis", "offsets": [50, 54], "confidence": 0.85 }
  //           ]
  //         },
  //         "keyphrases": [
  //           { "phrase": "爆震发动机", "score": 0.92, "method": "llm" }
  //         ],
  //         "tech_terms": [
  //           { "term": "爆震发动机", "lemma": "Pulse Detonation Engine", "synonyms": ["PDE"], "ontology_id": "IPC-F02K", "confidence": 0.95 }
  //         ],
  //         "quantities": [
  //           { "value": 15, "unit": "%", "context_sentence": "燃料消耗降低15%", "normalized_unit": "ratio" }
  //         ],
  //         "relations": [
  //           { "head": "爆震发动机", "relation": "应用于", "tail": "军事后勤装备", "evidence_span": "在军事后勤装备中的应用潜力" }
  //         ]
  //       },
  //       "E. 时空维度": {
  //         "published_at": "2024-05-15T00:00:00Z",
  //         "event_time": {
  //           "start": "2024-01-01T00:00:00Z",
  //           "end": "2024-05-15T00:00:00Z"
  //         },
  //         "geo": {
  //           "country": "中国",
  //           "province": "北京",
  //           "city": "北京"
  //         }
  //       },
  //       "F. 质量与安全": {
  //         "ocr_quality": 0.98,
  //         "language_confidence": 0.99,
  //         "credibility_score": 0.9,
  //         "security_class": "unclassified",
  //         "pii_flags": [],
  //         "redaction": { "applied": false }
  //       },
  //       "G. 算法特征层": {
  //         "tokens": {
  //           "unigrams": ["爆震", "发动机", "应用"],
  //           "bigrams": ["爆震发动机", "应用研究"],
  //           "trigrams": ["爆震发动机应用"]
  //         },
  //         "embedding": {
  //           "vector_id": "vec-00000001",
  //           "model": "bert-base-chinese",
  //           "dim": 768
  //         },
  //         "chunks": [
  //           { "chunk_id": "chunk-001", "text": "本文研究了爆震发动机在军事后勤装备中的应用潜力...", "offset": [0, 100], "page_no": 1, "embedding.vector_id": "vec-00000001" }
  //         ]
  //       },
  //       "H. 关系与引文": {
  //         "citations_out": [
  //           { "ref_title": "爆震发动机技术发展综述", "doi": "10.12345/pde.2023.001", "target_id": "uuid-00000002" }
  //         ],
  //         "citations_in_count": 5,
  //         "doc_relations": [
  //           { "type": "related_to", "target_id": "uuid-00000003" }
  //         ]
  //       },
  //       "I. 专家与标注": {
  //         "human_annotations": [
  //           { "label_set": "topic", "labels": ["军事能源保障"], "annotator": "expert01", "time": "2024-05-21T09:00:00Z", "notes": "确认属于军事能源保障主题" }
  //         ],
  //         "review_status": "human_checked",
  //         "review_notes": "已完成专家审核"
  //       }
  //     };
  //     break;

  //   case 'patent':
  //     title = '专利数据库示例';
  //     exampleData = {
  //       "A. 标识层": {
  //         "id": "uuid-00000002",
  //         "version": 1,
  //         "hash": "sha256-fedcba0987654321",
  //         "ingest_time": "2024-05-20T11:00:00Z",
  //         "pipeline_stage": "enriched"
  //       },
  //       "B. 来源与取数": {
  //         "source_type": "patent",
  //         "source_name": "中国专利数据库",
  //         "source_link": "https://patents.example.com/CN202410123456.7",
  //         "fetch_method": "api",
  //         "license": "restricted",
  //         "retrieval_time": "2024-05-20T11:05:00Z",
  //         "provenance": {
  //           "agent": "patent-fetcher-01",
  //           "batch_id": "batch-20240520-02",
  //           "data_center": "dc-shanghai"
  //         }
  //       },
  //       "C. 内容层": {
  //         "language": "zh-CN",
  //         "title": "一种军用后勤物资智能分拣系统",
  //         "abstract": "本发明公开了一种军用后勤物资智能分拣系统，包括图像识别模块、机械臂控制模块和仓储管理模块。该系统能够自动识别不同类型的军用物资并进行分类存储，显著提高了后勤仓库的作业效率。",
  //         "fulltext": "（完整专利文本内容）",
  //         "structure": {
  //           "sections": [
  //             { "heading": "技术领域", "text": "本发明涉及后勤保障技术领域...", "page_range": "1" },
  //             { "heading": "背景技术", "text": "现有的军用后勤物资分拣主要依赖人工...", "page_range": "1-2" }
  //           ],
  //           "tables": [],
  //           "figures": [],
  //           "references": []
  //         },
  //         "attachments": [],
  //         "page_count": 8,
  //         "word_count": 6200
  //       },
  //       "D. 结构化抽取层": {
  //         "entities": {
  //           "equipments": [
  //             { "name": "智能分拣系统", "normalized": "Intelligent Sorting System", "offsets": [10, 16], "confidence": 0.95 }
  //           ],
  //           "methods": [
  //             { "name": "图像识别", "normalized": "Image Recognition", "offsets": [25, 29], "confidence": 0.9 }
  //           ]
  //         },
  //         "keyphrases": [
  //           { "phrase": "军用后勤物资", "score": 0.88, "method": "llm" }
  //         ],
  //         "tech_terms": [
  //           { "term": "智能分拣", "lemma": "Intelligent Sorting", "synonyms": ["自动分拣"], "ontology_id": "IPC-B65G", "confidence": 0.92 }
  //         ],
  //         "quantities": [
  //           { "value": 40, "unit": "%", "context_sentence": "作业效率提高40%", "normalized_unit": "ratio" }
  //         ],
  //         "relations": [
  //           { "head": "智能分拣系统", "relation": "应用于", "tail": "军用后勤", "evidence_span": "军用后勤物资智能分拣系统" }
  //         ]
  //       },
  //       "E. 时空维度": {
  //         "published_at": "2024-05-10T00:00:00Z",
  //         "event_time": {
  //           "start": "2023-12-01T00:00:00Z",
  //           "end": "2024-05-10T00:00:00Z"
  //         },
  //         "geo": {
  //           "country": "中国",
  //           "province": "北京",
  //           "city": "北京"
  //         }
  //       },
  //       "F. 质量与安全": {
  //         "ocr_quality": 1.0,
  //         "language_confidence": 1.0,
  //         "credibility_score": 0.95,
  //         "security_class": "internal",
  //         "pii_flags": [],
  //         "redaction": { "applied": false }
  //       },
  //       "G. 算法特征层": {
  //         "tokens": {
  //           "unigrams": ["军用", "后勤", "物资", "智能", "分拣"],
  //           "bigrams": ["军用后勤", "智能分拣", "物资分拣"],
  //           "trigrams": ["军用后勤物资", "智能分拣系统"]
  //         },
  //         "embedding": {
  //           "vector_id": "vec-00000002",
  //           "model": "bert-base-chinese",
  //           "dim": 768
  //         },
  //         "chunks": [
  //           { "chunk_id": "chunk-002", "text": "本发明公开了一种军用后勤物资智能分拣系统...", "offset": [0, 100], "page_no": 1, "embedding.vector_id": "vec-00000002" }
  //         ]
  //       },
  //       "H. 关系与引文": {
  //         "citations_out": [],
  //         "citations_in_count": 0,
  //         "doc_relations": []
  //       },
  //       "I. 专家与标注": {
  //         "human_annotations": [
  //           { "label_set": "topic", "labels": ["仓储物流保障"], "annotator": "expert02", "time": "2024-05-21T10:00:00Z", "notes": "确认属于仓储物流保障主题" }
  //         ],
  //         "review_status": "human_checked",
  //         "review_notes": "已完成专家审核"
  //       }
  //     };
  //     break;

  //   case 'research':
  //     title = '科研项目数据示例';
  //     exampleData = {
  //       "A. 标识层": {
  //         "id": "uuid-00000003",
  //         "version": 1,
  //         "hash": "sha256-1234567890abcdef",
  //         "ingest_time": "2024-05-20T14:00:00Z",
  //         "pipeline_stage": "enriched"
  //       },
  //       "B. 来源与取数": {
  //         "source_type": "research_report",
  //         "source_name": "国防科技项目管理平台",
  //         "source_link": "https://projects.example.com/DZ2024JD001",
  //         "fetch_method": "api",
  //         "license": "proprietary",
  //         "retrieval_time": "2024-05-20T14:05:00Z",
  //         "provenance": {
  //           "agent": "project-fetcher-01",
  //           "batch_id": "batch-20240520-03",
  //           "data_center": "dc-xian"
  //         }
  //       },
  //       "C. 内容层": {
  //         "language": "zh-CN",
  //         "title": "后勤保障智能化决策支持系统关键技术研究",
  //         "abstract": "本项目旨在研究后勤保障智能化决策支持系统的关键技术，包括多源数据融合、智能预测算法和优化调度方法。通过构建原型系统，验证了技术方案的可行性，并在实际场景中进行了测试。",
  //         "fulltext": "（完整项目报告文本内容）",
  //         "structure": {
  //           "sections": [
  //             { "heading": "项目概述", "text": "本项目针对后勤保障中的决策问题...", "page_range": "1-2" },
  //             { "heading": "技术方案", "text": "采用以下技术方案解决关键问题...", "page_range": "2-5" }
  //           ],
  //           "tables": [],
  //           "figures": [],
  //           "references": []
  //         },
  //         "attachments": [
  //           { "type": "pdf", "uri": "https://projects.example.com/DZ2024JD001/附件1.pdf", "bytes": 2048000, "hash": "sha256-11111111" }
  //         ],
  //         "page_count": 50,
  //         "word_count": 35000
  //       },
  //       "D. 结构化抽取层": {
  //         "entities": {
  //           "projects": [
  //             { "name": "后勤保障智能化决策支持系统", "normalized": "Intelligent Decision Support System for Logistics", "offsets": [5, 18], "confidence": 0.95 }
  //           ],
  //           "methods": [
  //             { "name": "多源数据融合", "normalized": "Multi-source Data Fusion", "offsets": [30, 36], "confidence": 0.9 }
  //           ]
  //         },
  //         "keyphrases": [
  //           { "phrase": "智能决策支持系统", "score": 0.9, "method": "llm" }
  //         ],
  //         "tech_terms": [
  //           { "term": "数据融合", "lemma": "Data Fusion", "synonyms": ["信息融合"], "ontology_id": "GBT-1.2.3", "confidence": 0.88 }
  //         ],
  //         "quantities": [
  //           { "value": 25, "unit": "%", "context_sentence": "决策效率提升25%", "normalized_unit": "ratio" }
  //         ],
  //         "relations": [
  //           { "head": "智能决策支持系统", "relation": "应用于", "tail": "后勤保障", "evidence_span": "后勤保障智能化决策支持系统" }
  //         ]
  //       },
  //       "E. 时空维度": {
  //         "published_at": "2024-05-01T00:00:00Z",
  //         "event_time": {
  //           "start": "2024-01-01T00:00:00Z",
  //           "end": "2024-12-31T00:00:00Z"
  //         },
  //         "geo": {
  //           "country": "中国",
  //           "province": "陕西",
  //           "city": "西安"
  //         }
  //       },
  //       "F. 质量与安全": {
  //         "ocr_quality": 1.0,
  //         "language_confidence": 1.0,
  //         "credibility_score": 0.98,
  //         "security_class": "confidential",
  //         "pii_flags": [],
  //         "redaction": { "applied": false }
  //       },
  //       "G. 算法特征层": {
  //         "tokens": {
  //           "unigrams": ["后勤", "保障", "智能", "决策", "支持"],
  //           "bigrams": ["后勤保障", "智能决策", "支持系统"],
  //           "trigrams": ["后勤保障智能化", "智能决策支持"]
  //         },
  //         "embedding": {
  //           "vector_id": "vec-00000003",
  //           "model": "bert-base-chinese",
  //           "dim": 768
  //         },
  //         "chunks": [
  //           { "chunk_id": "chunk-003", "text": "本项目旨在研究后勤保障智能化决策支持系统...", "offset": [0, 100], "page_no": 1, "embedding.vector_id": "vec-00000003" }
  //         ]
  //       },
  //       "H. 关系与引文": {
  //         "citations_out": [],
  //         "citations_in_count": 0,
  //         "doc_relations": [
  //           { "type": "related_to", "target_id": "uuid-00000001" }
  //         ]
  //       },
  //       "I. 专家与标注": {
  //         "human_annotations": [
  //           { "label_set": "topic", "labels": ["后勤大数据保障"], "annotator": "expert03", "time": "2024-05-21T11:00:00Z", "notes": "确认属于后勤大数据保障主题" }
  //         ],
  //         "review_status": "human_checked",
  //         "review_notes": "已完成专家审核"
  //       }
  //     };
  //     break;

  //   case 'intelligence':
  //     title = '开源情报数据示例';
  //     exampleData = {
  //       "A. 标识层": {
  //         "id": "uuid-00000004",
  //         "version": 1,
  //         "hash": "sha256-abcdef1234567890",
  //         "ingest_time": "2024-05-20T15:00:00Z",
  //         "pipeline_stage": "enriched"
  //       },
  //       "B. 来源与取数": {
  //         "source_type": "web_post",
  //         "source_name": "军事科技观察网站",
  //         "source_link": "https://intel.example.com/analysis/20240519",
  //         "fetch_method": "crawler",
  //         "license": "open",
  //         "retrieval_time": "2024-05-20T15:05:00Z",
  //         "provenance": {
  //           "agent": "web-crawler-01",
  //           "batch_id": "batch-20240520-04",
  //           "data_center": "dc-guangzhou"
  //         }
  //       },
  //       "C. 内容层": {
  //         "language": "zh-CN",
  //         "title": "美军后勤保障数字化转型最新进展分析",
  //         "abstract": "本文分析了美军在后勤保障领域的数字化转型最新进展，重点关注人工智能、大数据和物联网技术的应用情况，以及对我国的启示。",
  //         "fulltext": "（完整情报分析文本内容）",
  //         "structure": {
  //           "sections": [
  //             { "heading": "引言", "text": "美军近年来大力推进后勤保障领域的数字化转型...", "page_range": "1" },
  //             { "heading": "技术应用分析", "text": "在人工智能方面，美军主要应用了...", "page_range": "1-3" }
  //           ],
  //           "tables": [],
  //           "figures": [],
  //           "references": [
  //             { "raw": "[1] 美军联合后勤司令部. 后勤保障4.0白皮书. 2024年." }
  //           ]
  //         },
  //         "attachments": [],
  //         "page_count": 15,
  //         "word_count": 12000
  //       },
  //       "D. 结构化抽取层": {
  //         "entities": {
  //           "orgs": [
  //             { "name": "美军联合后勤司令部", "normalized": "U.S. Joint Logistics Command", "offsets": [50, 58], "confidence": 0.95 }
  //           ],
  //           "methods": [
  //             { "name": "数字化转型", "normalized": "Digital Transformation", "offsets": [25, 30], "confidence": 0.9 }
  //           ]
  //         },
  //         "keyphrases": [
  //           { "phrase": "后勤保障数字化", "score": 0.88, "method": "llm" }
  //         ],
  //         "tech_terms": [
  //           { "term": "人工智能", "lemma": "Artificial Intelligence", "synonyms": ["AI"], "ontology_id": "GBT-4.5.6", "confidence": 0.95 }
  //         ],
  //         "quantities": [],
  //         "relations": [
  //           { "head": "美军", "relation": "推进", "tail": "后勤保障数字化转型", "evidence_span": "美军近年来大力推进后勤保障领域的数字化转型" }
  //         ]
  //       },
  //       "E. 时空维度": {
  //         "published_at": "2024-05-19T00:00:00Z",
  //         "event_time": {
  //           "start": "2024-01-01T00:00:00Z",
  //           "end": "2024-05-19T00:00:00Z"
  //         },
  //         "geo": {
  //           "country": "美国",
  //           "province": "华盛顿特区",
  //           "city": "华盛顿"
  //         }
  //       },
  //       "F. 质量与安全": {
  //         "ocr_quality": 1.0,
  //         "language_confidence": 1.0,
  //         "credibility_score": 0.85,
  //         "security_class": "unclassified",
  //         "pii_flags": [],
  //         "redaction": { "applied": false }
  //       },
  //       "G. 算法特征层": {
  //         "tokens": {
  //           "unigrams": ["美军", "后勤", "保障", "数字化", "转型"],
  //           "bigrams": ["美军后勤", "保障数字化", "转型分析"],
  //           "trigrams": ["美军后勤保障", "后勤保障数字化"]
  //         },
  //         "embedding": {
  //           "vector_id": "vec-00000004",
  //           "model": "bert-base-chinese",
  //           "dim": 768
  //         },
  //         "chunks": [
  //           { "chunk_id": "chunk-004", "text": "本文分析了美军在后勤保障领域的数字化转型最新进展...", "offset": [0, 100], "page_no": 1, "embedding.vector_id": "vec-00000004" }
  //         ]
  //       },
  //       "H. 关系与引文": {
  //         "citations_out": [
  //           { "ref_title": "后勤保障4.0白皮书", "target_id": "uuid-00000005" }
  //         ],
  //         "citations_in_count": 12,
  //         "doc_relations": []
  //       },
  //       "I. 专家与标注": {
  //         "human_annotations": [
  //           { "label_set": "topic", "labels": ["军事设施保障"], "annotator": "expert04", "time": "2024-05-21T12:00:00Z", "notes": "确认属于军事设施保障主题" }
  //         ],
  //         "review_status": "human_checked",
  //         "review_notes": "已完成专家审核"
  //       }
  //     };
  //     break;

  //   case 'social':
  //     title = '社交媒体数据示例';
  //     exampleData = {
  //       "A. 标识层": {
  //         "id": "uuid-00000005",
  //         "version": 1,
  //         "hash": "sha256-fedcba0987654321",
  //         "ingest_time": "2024-05-20T16:00:00Z",
  //         "pipeline_stage": "enriched"
  //       },
  //       "B. 来源与取数": {
  //         "source_type": "web_post",
  //         "source_name": "军事爱好者论坛",
  //         "source_link": "https://forum.example.com/threads/123456",
  //         "fetch_method": "crawler",
  //         "license": "unknown",
  //         "retrieval_time": "2024-05-20T16:05:00Z",
  //         "provenance": {
  //           "agent": "social-crawler-01",
  //           "batch_id": "batch-20240520-05",
  //           "data_center": "dc-chengdu"
  //         }
  //       },
  //       "C. 内容层": {
  //         "language": "zh-CN",
  //         "title": "对新型军用无人机后勤保障的几点思考",
  //         "abstract": "讨论了新型军用无人机在后勤保障中的应用，特别是在物资运输和战场支援方面的潜力，以及相关的技术挑战。",
  //         "fulltext": "（完整论坛帖子内容）",
  //         "structure": {
  //           "sections": [
  //             { "heading": "楼主", "text": "最近看到新闻报道了新型军用无人机的列装...", "page_range": "1" },
  //             { "heading": "回复1", "text": "无人机在后勤保障中确实有很大潜力...", "page_range": "1" }
  //           ],
  //           "tables": [],
  //           "figures": [],
  //           "references": []
  //         },
  //         "attachments": [],
  //         "page_count": 3,
  //         "word_count": 2500
  //       },
  //       "D. 结构化抽取层": {
  //         "entities": {
  //           "equipments": [
  //             { "name": "军用无人机", "normalized": "Military UAV", "offsets": [5, 10], "confidence": 0.95 }
  //           ],
  //           "methods": [
  //             { "name": "物资运输", "normalized": "Material Transportation", "offsets": [25, 29], "confidence": 0.85 }
  //           ]
  //         },
  //         "keyphrases": [
  //           { "phrase": "军用无人机", "score": 0.92, "method": "llm" }
  //         ],
  //         "tech_terms": [
  //           { "term": "无人机", "lemma": "Unmanned Aerial Vehicle", "synonyms": ["UAV"], "ontology_id": "GBT-7.8.9", "confidence": 0.9 }
  //         ],
  //         "quantities": [],
  //         "relations": [
  //           { "head": "军用无人机", "relation": "应用于", "tail": "后勤保障", "evidence_span": "在后勤保障中的应用" }
  //         ]
  //       },
  //       "E. 时空维度": {
  //         "published_at": "2024-05-18T14:30:00Z",
  //         "event_time": {
  //           "start": "2024-05-18T00:00:00Z",
  //           "end": "2024-05-18T23:59:59Z"
  //         },
  //         "geo": {
  //           "country": "中国",
  //           "province": "北京",
  //           "city": "北京"
  //         }
  //       },
  //       "F. 质量与安全": {
  //         "ocr_quality": 1.0,
  //         "language_confidence": 1.0,
  //         "credibility_score": 0.6,
  //         "security_class": "unclassified",
  //         "pii_flags": [
  //           { "type": "name" }
  //         ],
  //         "redaction": { "applied": true }
  //       },
  //       "G. 算法特征层": {
  //         "tokens": {
  //           "unigrams": ["军用", "无人机", "后勤", "保障", "思考"],
  //           "bigrams": ["军用无人机", "后勤保障", "几点思考"],
  //           "trigrams": ["军用无人机后勤", "后勤保障几点"]
  //         },
  //         "embedding": {
  //           "vector_id": "vec-00000005",
  //           "model": "bert-base-chinese",
  //           "dim": 768
  //         },
  //         "chunks": [
  //           { "chunk_id": "chunk-005", "text": "讨论了新型军用无人机在后勤保障中的应用...", "offset": [0, 100], "page_no": 1, "embedding.vector_id": "vec-00000005" }
  //         ]
  //       },
  //       "H. 关系与引文": {
  //         "citations_out": [],
  //         "citations_in_count": 8,
  //         "doc_relations": []
  //       },
  //       "I. 专家与标注": {
  //         "human_annotations": [
  //           { "label_set": "topic", "labels": ["运输投送保障"], "annotator": "expert05", "time": "2024-05-21T13:00:00Z", "notes": "确认属于运输投送保障主题" }
  //         ],
  //         "review_status": "human_checked",
  //         "review_notes": "已完成专家审核"
  //       }
  //     };
  //     break;

  //   default:
  //     title = '未知源数据';
  //     exampleData = {
  //       "error": "未找到对应的源数据示例"
  //     };
  // }

  // 生成HTML内容
  return `
    <div>
      <h3>${title}</h3>
      <pre>${JSON.stringify(exampleData, null, 2)}</pre>
    </div>
  `;
}

// 系统设置页面初始化
function initSettingsPage() {
  console.log('初始化系统设置页面');

  // 绑定设置保存事件
  const settingsForm = document.getElementById('settings-form');
  if (settingsForm) {
    settingsForm.addEventListener('submit', saveSettings);
  }
}

// 保存设置
function saveSettings(event) {
  event.preventDefault();
  showMessage('设置已保存', 'success');
}

// 移动端底部导航切换
function switchTab(tabName) {
  // 移除所有活动状态
  const navItems = document.querySelectorAll('.nav-item');
  navItems.forEach(item => {
    item.classList.remove('active');
  });

  // 添加当前活动状态
  const activeItem = document.querySelector(`.nav-item[data-tab="${tabName}"]`);
  if (activeItem) {
    activeItem.classList.add('active');
  }

  console.log(`切换到标签: ${tabName}`);
}

// 绑定页签切换事件
function bindTabEvents() {
  // 页签切换
  const tabButtons = document.querySelectorAll('.tab-btn');
  tabButtons.forEach(button => {
    button.addEventListener('click', function () {
      const tabId = this.dataset.tab;

      // 移除所有活动状态
      tabButtons.forEach(btn => btn.classList.remove('active'));
      document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));

      // 添加当前活动状态
      this.classList.add('active');
      document.getElementById(`tab-${tabId}`).classList.add('active');
    });
  });

  // 模型温度滑块
  const temperatureSlider = document.querySelector('input[type="range"]');
  if (temperatureSlider) {
    temperatureSlider.addEventListener('input', function () {
      document.getElementById('temperature-value').textContent = this.value;
    });
  }

  // 战略契合度滑块
  const fitSlider = document.querySelector('#tab-evaluation input[type="range"]');
  if (fitSlider) {
    fitSlider.addEventListener('input', function () {
      document.getElementById('fit-value').textContent = this.value;
    });
  }

  // 树形结构展开/折叠
  const treeHeaders = document.querySelectorAll('.tree-header');
  treeHeaders.forEach(header => {
    header.addEventListener('click', function () {
      this.classList.toggle('expanded');
      const children = this.nextElementSibling;
      if (children) {
        children.classList.toggle('expanded');
      }
    });
  });

  // 提示词类别切换
  const promptCategory = document.getElementById('prompt-category');
  if (promptCategory) {
    promptCategory.addEventListener('change', function () {
      const themePrompt = document.getElementById('theme-prompt');
      const techPrompt = document.getElementById('tech-prompt');
      const predictionPrompt = document.getElementById('prediction-prompt');

      // 隐藏所有提示词模板
      themePrompt.style.display = 'none';
      techPrompt.style.display = 'none';
      predictionPrompt.style.display = 'none';

      // 根据选择显示对应的提示词模板
      if (this.value === 'theme') {
        themePrompt.style.display = 'block';
      } else if (this.value === 'tech') {
        techPrompt.style.display = 'block';
      } else if (this.value === 'prediction') {
        predictionPrompt.style.display = 'block';
      }
    });
  }

  // 提交运行按钮
  const runPromptBtn = document.getElementById('run-prompt');
  if (runPromptBtn) {
    runPromptBtn.addEventListener('click', function () {
      // 显示加载状态
      this.innerHTML = '<span class="spinner"></span> 提交中...';
      this.disabled = true;

      //获取当前选中的关键词模板
      const promptCategory = document.getElementById('prompt-category').value;
      // 模拟提交过程
      // setTimeout(() => {
      // 切换到进度页签


      // 提交任务
      request('api/Analysis/submitTask', 'POST', {
        keyword_template_id: promptCategory
      }).then(data => {
        if (data.code === 1) {
          tabButtons.forEach(btn => btn.classList.remove('active'));
          document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));

          const progressTabBtn = document.querySelector('.tab-btn[data-tab="progress"]');
          const progressTab = document.getElementById('tab-progress');

          if (progressTabBtn && progressTab) {
            progressTabBtn.classList.add('active');
            progressTab.classList.add('active');
          }
          // 恢复按钮状态
          this.innerHTML = '提交运行';
          this.disabled = false;
          getTaskList();
          // requestModelApi(data.data);
          showMessage('任务已提交，可在进度页签查看', 'success');
        } else {
          showMessage('提交失败: ' + data.msg, 'error');
        }
      }).catch(error => {
        showMessage('提交失败: ' + error, 'error');
      });
    });
  }

  //请求大模型接口
  // function requestModelApi(params) { 
  //   //取出task_id 并移除
  //   var taskId = params.currentTaskId 
  //   modeRequest(
  //     modelUrl + 'v1/workflows/run',
  //     'POST',
  //     {
  //       "inputs": params,
  //       "response_mode": "blocking",
  //       "user": "abc-123"
  //     }
  //   ).then(data => {  
  //     let result = data.data
  //     let outputs = result.outputs

  //   }).catch(error => { 
  //   });
  // }

  // 保存模板按钮
  const savePromptBtn = document.getElementById('save-prompt');
  if (savePromptBtn) {
    savePromptBtn.addEventListener('click', function () {
      // 弹出提示框要求用户输入模板名称
      const templateName = prompt('请输入模板名称:');
      if (templateName) {
        //获取当前选中的提示词内容
        const promptContent = document.querySelector('#prompt-content').value;
        if (!promptContent) {
          showMessage('提示词内容不能为空', 'error');
          return;
        }

        request('api/Analysis/addKeywordTemplate', 'POST', {
          name: templateName,
          data_demo: promptContent
        }).then(data => {
          if (data.code === 1) {
            initPromptFramework();//初始化提示词框架
            showMessage('模板已保存: ' + templateName, 'success');
          } else {
            showMessage('保存失败: ' + data.msg, 'error');
          }
        }).catch(error => {
          showMessage('保存失败: ' + error, 'error');
        });
      }
    });
  }

  // 页面加载时恢复自定义模板
  // window.addEventListener('DOMContentLoaded', function () {
  //   const customTemplates = JSON.parse(localStorage.getItem('customTemplates') || '{}');
  //   const promptCategory = document.getElementById('prompt-category'); 
  //   // 为每个自定义模板创建下拉选项
  //   for (const key in customTemplates) {
  //     const template = customTemplates[key];
  //     const newOption = document.createElement('option');
  //     newOption.value = key;
  //     newOption.textContent = template.name;
  //     promptCategory.appendChild(newOption);
  //   }

  //   // 添加自定义模板的显示逻辑
  //   promptCategory.addEventListener('change', function () {
  //     const selectedValue = this.value;

  //     // 如果选中的是自定义模板
  //     if (selectedValue.startsWith('custom_')) {
  //       const customTemplates = JSON.parse(localStorage.getItem('customTemplates') || '{}');
  //       const template = customTemplates[selectedValue];

  //       if (template) {
  //         // 隐藏所有内置模板
  //         document.getElementById('theme-prompt').style.display = 'none';
  //         document.getElementById('tech-prompt').style.display = 'none';
  //         document.getElementById('prediction-prompt').style.display = 'none';

  //         // 创建或显示自定义模板
  //         let customPromptDiv = document.getElementById('custom-prompt');
  //         if (!customPromptDiv) {
  //           customPromptDiv = document.createElement('div');
  //           customPromptDiv.className = 'prompt-template';
  //           customPromptDiv.id = 'custom-prompt';
  //           customPromptDiv.innerHTML = `
  //             <div class="form-group">
  //               <label class="form-label">自定义提示词模板</label>
  //               <textarea class="textarea-field" rows="20">${template.content}</textarea>
  //             </div>
  //           `;
  //           document.querySelector('#tab-prompt').insertBefore(customPromptDiv, document.querySelector('#tab-prompt .form-group:last-child'));
  //         } else {
  //           customPromptDiv.querySelector('textarea').value = template.content;
  //           customPromptDiv.style.display = 'block';
  //         }
  //       }
  //     }
  //   });
  // });

  // 绑定进度详情按钮事件
  const progressDetailButtons = document.querySelectorAll('.progress-detail-btn');
  progressDetailButtons.forEach(button => {
    button.addEventListener('click', function () {
      const taskId = this.dataset.task;
      showProgressDetail(taskId);
    });
  });

  // 绑定关闭进度详情事件
  const closeProgressDetail = document.getElementById('close-progress-detail');
  if (closeProgressDetail) {
    closeProgressDetail.addEventListener('click', function () {
      document.getElementById('progress-detail-container').style.display = 'none';
    });
  }

  // 绑定模态框关闭事件
  const closeModal = document.getElementById('close-modal');
  if (closeModal) {
    closeModal.addEventListener('click', function () {
      document.getElementById('progress-modal').style.display = 'none';
    });
  }

  // 绑定技术主题详情模态框关闭事件
  const closeThemeModal = document.getElementById('close-theme-modal');
  if (closeThemeModal) {
    closeThemeModal.addEventListener('click', function () {
      document.getElementById('theme-detail-modal').style.display = 'none';
    });
  }

  // 点击模态框背景关闭
  const modal = document.getElementById('progress-modal');
  if (modal) {
    modal.addEventListener('click', function (event) {
      if (event.target === modal) {
        modal.style.display = 'none';
      }
    });
  }

  // 点击技术主题详情模态框背景关闭
  const themeModal = document.getElementById('theme-detail-modal');
  if (themeModal) {
    themeModal.addEventListener('click', function (event) {
      if (event.target === themeModal) {
        themeModal.style.display = 'none';
      }
    });
  }

  // 源数据选择页签中的复选框事件
  const dataSourceCheckboxes = document.querySelectorAll('#tab-datasource input[type="checkbox"]');
  dataSourceCheckboxes.forEach(checkbox => {
    checkbox.addEventListener('change', function () {
      const title = this.closest('.list-item').querySelector('.list-title').textContent;
      let exampleId = '';

      // 根据标题确定示例ID
      if (title.includes('期刊论文')) {
        exampleId = 'journal-example';
      } else if (title.includes('专利')) {
        exampleId = 'patent-example';
      } else if (title.includes('科研项目')) {
        exampleId = 'research-example';
      } else if (title.includes('开源情报')) {
        exampleId = 'intelligence-example';
      } else if (title.includes('社交媒体')) {
        exampleId = 'social-example';
      }

      // 显示或隐藏对应的示例
      const exampleDiv = document.getElementById(exampleId);
      if (exampleDiv) {
        exampleDiv.style.display = this.checked ? 'block' : 'none';
      }
    });
  });

  // 初始化时显示已选中的源数据示例
  setTimeout(() => {
    dataSourceCheckboxes.forEach(checkbox => {
      if (checkbox.checked) {
        checkbox.dispatchEvent(new Event('change'));
      }
    });
  }, 100);

  // 绑定技术主题查看详情按钮事件
  const detailButtons = document.querySelectorAll('.detail-btn');
  detailButtons.forEach(button => {
    button.addEventListener('click', function () {
      const themeName = this.dataset.theme;
      showThemeDetail(themeName);
    });
  });
}

// 显示进度详情
function showProgressDetail(taskId) {
  // 这里可以添加逻辑来决定是使用弹窗还是展开式
  // 目前我们提供两种方式，可以通过修改这个函数来切换

  // 方式1: 展开式显示
  showProgressDetailExpanded(taskId);

  // 方式2: 弹窗显示（注释掉上面一行，取消注释下面一行来使用弹窗）
  // showProgressDetailModal(taskId);
}

// 展开式显示进度详情
function showProgressDetailExpanded(taskId) {
  const container = document.getElementById('progress-detail-container');
  const content = document.getElementById('progress-detail-content');

  // 显示加载状态
  content.innerHTML = '<div class="loading"><div class="spinner"></div></div>';
  container.style.display = 'block';

  // 模拟数据加载
  setTimeout(() => {
    content.innerHTML = generateProgressDetailContent(taskId);
  }, 500);
}

// 弹窗式显示进度详情
function showProgressDetailModal(taskId) {
  const modal = document.getElementById('progress-modal');
  const content = document.getElementById('modal-progress-detail-content');

  // 显示加载状态
  content.innerHTML = '<div class="loading"><div class="spinner"></div></div>';
  modal.style.display = 'flex';

  // 模拟数据加载
  setTimeout(() => {
    content.innerHTML = generateProgressDetailContent(taskId);
  }, 500);
}

// 生成进度详情内容
function generateProgressDetailContent(taskId) {
  // 根据任务ID生成不同的详情内容
  let title, status, progress, startTime, endTime, steps;

  switch (taskId) {
    case '20240115-001':
      title = '后勤大数据分析任务';
      status = '进行中';
      progress = 65;
      startTime = '2024-01-15 09:00';
      endTime = '-';
      steps = [
        { name: '资料拉取', status: 'completed', time: '09:00-09:30' },
        { name: '数据清洗', status: 'completed', time: '09:30-10:15' },
        { name: '特征提取', status: 'completed', time: '10:15-11:00' },
        { name: '定量分析', status: 'processing', time: '11:00-12:30' },
        { name: '结果分析', status: 'pending', time: '12:30-13:30' },
        { name: '报告生成', status: 'pending', time: '13:30-14:00' }
      ];
      break;
    case '20240114-002':
      title = '智能仓储系统识别';
      status = '已完成';
      progress = 100;
      startTime = '2024-01-14 08:00';
      endTime = '2024-01-14 15:30';
      steps = [
        { name: '资料拉取', status: 'completed', time: '08:00-08:45' },
        { name: '数据清洗', status: 'completed', time: '08:45-09:30' },
        { name: '特征提取', status: 'completed', time: '09:30-10:30' },
        { name: '定量分析', status: 'completed', time: '10:30-12:00' },
        { name: '结果分析', status: 'completed', time: '12:00-13:30' },
        { name: '报告生成', status: 'completed', time: '13:30-15:30' }
      ];
      break;
    case '20240114-001':
      title = '无人配送技术识别';
      status = '已完成';
      progress = 100;
      startTime = '2024-01-14 07:00';
      endTime = '2024-01-14 09:45';
      steps = [
        { name: '资料拉取', status: 'completed', time: '07:00-07:30' },
        { name: '数据清洗', status: 'completed', time: '07:30-08:00' },
        { name: '特征提取', status: 'completed', time: '08:00-08:30' },
        { name: '定量分析', status: 'completed', time: '08:30-09:00' },
        { name: '结果分析', status: 'completed', time: '09:00-09:30' },
        { name: '报告生成', status: 'completed', time: '09:30-09:45' }
      ];
      break;
    case '20240116-001':
      title = '高精度定位导航技术识别';
      status = '已完成';
      progress = 100;
      startTime = '2024-01-16 09:00';
      endTime = '2024-01-16 14:20';
      steps = [
        { name: '资料拉取', status: 'completed', time: '09:00-09:45' },
        { name: '数据清洗', status: 'completed', time: '09:45-10:30' },
        { name: '特征提取', status: 'completed', time: '10:30-11:30' },
        { name: '定量分析', status: 'completed', time: '11:30-12:45' },
        { name: '结果分析', status: 'completed', time: '12:45-13:30' },
        { name: '报告生成', status: 'completed', time: '13:30-14:20' }
      ];
      break;
    case '20240117-001':
      title = '智能预测维护技术识别';
      status = '已完成';
      progress = 100;
      startTime = '2024-01-17 08:30';
      endTime = '2024-01-17 16:45';
      steps = [
        { name: '资料拉取', status: 'completed', time: '08:30-09:15' },
        { name: '数据清洗', status: 'completed', time: '09:15-10:00' },
        { name: '特征提取', status: 'completed', time: '10:00-11:15' },
        { name: '定量分析', status: 'completed', time: '11:15-13:00' },
        { name: '结果分析', status: 'completed', time: '13:00-14:30' },
        { name: '报告生成', status: 'completed', time: '14:30-16:45' }
      ];
      break;
    default:
      title = '未知任务';
      status = '未知';
      progress = 0;
      startTime = '-';
      endTime = '-';
      steps = [];
  }

  // 生成HTML内容
  let stepsHtml = '';
  steps.forEach(step => {
    let statusClass = '';
    let statusText = '';

    switch (step.status) {
      case 'completed':
        statusClass = 'status-completed';
        statusText = '已完成';
        break;
      case 'processing':
        statusClass = 'status-processing';
        statusText = '进行中';
        break;
      case 'pending':
        statusClass = 'status-pending';
        statusText = '待处理';
        break;
    }

    stepsHtml += `
      <div class="progress-item">
        <div class="progress-title">${step.name}</div>
        <div class="progress-meta">
          <span class="progress-status ${statusClass}">${statusText}</span>
          <span style="float: right;">${step.time}</span>
        </div>
      </div>
    `;
  });

  return `
    <div class="card">
      <div class="list-item">
        <div>
          <div class="list-title">${title}</div>
          <div class="list-meta">任务ID: ${taskId}</div>
        </div>
        <div>
          <span class="status-badge ${status === '已完成' ? 'status-confirmed' : 'status-review'}">${status}</span>
        </div>
      </div>
      
      <div class="form-group">
        <label class="form-label">任务进度</label>
        <div class="progress-bar">
          <div style="background-color: #2E5A3E; height: 8px; width: ${progress}%; border-radius: 4px;"></div>
        </div>
        <div class="text-right">${progress}%</div>
      </div>
      
      <div class="row">
        <div class="col-6">
          <div class="form-group">
            <label class="form-label">开始时间</label>
            <div>${startTime}</div>
          </div>
        </div>
        <div class="col-6">
          <div class="form-group">
            <label class="form-label">结束时间</label>
            <div>${endTime}</div>
          </div>
        </div>
      </div>
      
      <div class="form-group">
        <label class="form-label">执行步骤</label>
        ${stepsHtml}
      </div>
      
      <div class="form-group">
        <button class="btn btn-block btn-secondary" onclick="toggleViewMode('${taskId}')">切换显示方式</button>
      </div>
    </div>
  `;
}

// 切换显示方式
function toggleViewMode(taskId) {
  // 获取当前显示方式
  const modal = document.getElementById('progress-modal');
  const container = document.getElementById('progress-detail-container');

  if (modal.style.display === 'flex') {
    // 当前是弹窗模式，切换到展开模式
    modal.style.display = 'none';
    showProgressDetailExpanded(taskId);
  } else {
    // 当前是展开模式，切换到弹窗模式
    container.style.display = 'none';
    showProgressDetailModal(taskId);
  }
}

// 显示技术主题详情弹窗
function showThemeDetail(themeName) {
  const modal = document.getElementById('theme-detail-modal');
  const content = document.getElementById('modal-theme-detail-content');

  // 显示加载状态
  content.innerHTML = '<div class="loading"><div class="spinner"></div></div>';
  modal.style.display = 'flex';

  // 模拟数据加载
  setTimeout(() => {
    content.innerHTML = generateThemeDetailContent(themeName);
  }, 500);
}

// 生成技术主题详情内容
function generateThemeDetailContent(themeName) {
  // 根据主题名称生成不同的详情内容
  let title, description, category, sources, confidence, status, relatedThemes;

  // 这里可以根据实际需求来设置不同的主题详情
  switch (themeName) {
    case '军需保障装备专用技术体系':
      title = '军需保障装备专用技术体系';
      description = '该技术体系主要涉及军需保障装备的研发、生产和维护，包括单兵防护装备、野战食品和被装等。';
      category = '军需保障';
      sources = ['期刊论文', '专利数据', '科研报告'];
      confidence = '高';
      status = '已确认';
      relatedThemes = ['单兵防护技术', '野战食品技术', '被装技术'];
      break;
    case '单兵防护技术':
      title = '单兵防护技术';
      description = '单兵防护技术是军需保障的重要组成部分，主要涉及防弹衣、头盔、防化服等装备的技术研发。';
      category = '军需保障';
      sources = ['期刊论文', '专利数据'];
      confidence = '高';
      status = '已确认';
      relatedThemes = ['防弹衣材料技术', '头盔防护技术', '防化服技术'];
      break;
    case '防弹衣材料技术':
      title = '防弹衣材料技术';
      description = '防弹衣材料技术专注于开发新型高性能防护材料，如凯夫拉纤维、超高分子量聚乙烯等。';
      category = '军需保障';
      sources = ['期刊论文', '专利数据'];
      confidence = '高';
      status = '已确认';
      relatedThemes = ['材料科学', '纺织技术'];
      break;
    case '头盔防护技术':
      title = '头盔防护技术';
      description = '头盔防护技术致力于提高头盔的防弹性能、舒适性和多功能性。';
      category = '军需保障';
      sources = ['期刊论文', '专利数据'];
      confidence = '中';
      status = '审核中';
      relatedThemes = ['材料科学', '人体工程学'];
      break;
    case '防化服技术':
      title = '防化服技术';
      description = '防化服技术专注于开发能够防护化学、生物、放射性物质的防护服装。';
      category = '军需保障';
      sources = ['期刊论文', '科研报告'];
      confidence = '中';
      status = '审核中';
      relatedThemes = ['材料科学', '化学防护'];
      break;
    case '野战食品技术':
      title = '野战食品技术';
      description = '野战食品技术涉及野战环境下食品的营养配比、保鲜包装和快速加热等技术。';
      category = '军需保障';
      sources = ['期刊论文', '科研报告'];
      confidence = '高';
      status = '已确认';
      relatedThemes = ['营养配比技术', '保鲜包装技术', '快速加热技术'];
      break;
    case '营养配比技术':
      title = '营养配比技术';
      description = '营养配比技术专注于根据不同作战环境和任务需求，科学配比食品营养成分。';
      category = '军需保障';
      sources = ['期刊论文', '科研报告'];
      confidence = '高';
      status = '已确认';
      relatedThemes = ['营养学', '食品科学'];
      break;
    case '保鲜包装技术':
      title = '保鲜包装技术';
      description = '保鲜包装技术致力于在野战环境下保持食品的新鲜度和营养价值。';
      category = '军需保障';
      sources = ['期刊论文', '专利数据'];
      confidence = '中';
      status = '审核中';
      relatedThemes = ['包装技术', '食品科学'];
      break;
    case '快速加热技术':
      title = '快速加热技术';
      description = '快速加热技术使士兵在野战环境下能够快速加热食品，提高用餐便利性。';
      category = '军需保障';
      sources = ['专利数据', '科研报告'];
      confidence = '中';
      status = '审核中';
      relatedThemes = ['加热技术', '能源技术'];
      break;
    case '被装技术':
      title = '被装技术';
      description = '被装技术涉及军用服装的设计、材料选择和功能集成，如智能调温、防水透气等。';
      category = '军需保障';
      sources = ['期刊论文', '专利数据'];
      confidence = '高';
      status = '已确认';
      relatedThemes = ['智能调温纤维技术', '防水透气材料技术'];
      break;
    case '智能调温纤维技术':
      title = '智能调温纤维技术';
      description = '智能调温纤维技术能够根据环境温度自动调节服装的保温性能。';
      category = '军需保障';
      sources = ['期刊论文', '专利数据'];
      confidence = '中';
      status = '审核中';
      relatedThemes = ['材料科学', '智能纺织品'];
      break;
    case '防水透气材料技术':
      title = '防水透气材料技术';
      description = '防水透气材料技术使军服具备防水性能的同时保持良好的透气性。';
      category = '军需保障';
      sources = ['期刊论文', '科研报告'];
      confidence = '高';
      status = '已确认';
      relatedThemes = ['材料科学', '纺织技术'];
      break;
    case '军事能源保障装备专用技术体系':
      title = '军事能源保障装备专用技术体系';
      description = '该技术体系涵盖野战电源、燃料供应和新能源技术，保障军事行动的能源需求。';
      category = '军事能源保障';
      sources = ['期刊论文', '专利数据', '科研报告'];
      confidence = '高';
      status = '已确认';
      relatedThemes = ['野战电源技术', '燃料供应技术', '新能源技术'];
      break;
    case '野战电源技术':
      title = '野战电源技术';
      description = '野战电源技术涉及便携式发电、储能电池和太阳能充电等技术。';
      category = '军事能源保障';
      sources = ['期刊论文', '专利数据'];
      confidence = '高';
      status = '已确认';
      relatedThemes = ['便携式发电技术', '储能电池技术', '太阳能充电技术'];
      break;
    case '便携式发电技术':
      title = '便携式发电技术';
      description = '便携式发电技术专注于开发轻便、高效的发电设备，满足野战环境下的电力需求。';
      category = '军事能源保障';
      sources = ['期刊论文', '专利数据'];
      confidence = '高';
      status = '已确认';
      relatedThemes = ['能源技术', '电子工程'];
      break;
    case '储能电池技术':
      title = '储能电池技术';
      description = '储能电池技术致力于提高电池的能量密度、安全性和环境适应性。';
      category = '军事能源保障';
      sources = ['期刊论文', '专利数据'];
      confidence = '高';
      status = '已确认';
      relatedThemes = ['电化学', '材料科学'];
      break;
    case '太阳能充电技术':
      title = '太阳能充电技术';
      description = '太阳能充电技术利用太阳能为野战设备提供清洁、可持续的电力供应。';
      category = '军事能源保障';
      sources = ['期刊论文', '科研报告'];
      confidence = '中';
      status = '审核中';
      relatedThemes = ['光伏技术', '能源技术'];
      break;
    case '燃料供应技术':
      title = '燃料供应技术';
      description = '燃料供应技术涉及油料净化、快速补给和储存等技术，保障军事装备的燃料需求。';
      category = '军事能源保障';
      sources = ['期刊论文', '科研报告'];
      confidence = '高';
      status = '已确认';
      relatedThemes = ['油料净化技术', '快速补给技术', '燃料储存技术'];
      break;
    case '油料净化技术':
      title = '油料净化技术';
      description = '油料净化技术去除燃料中的杂质和水分，确保燃料质量。';
      category = '军事能源保障';
      sources = ['期刊论文', '专利数据'];
      confidence = '高';
      status = '已确认';
      relatedThemes = ['化学工程', '过滤技术'];
      break;
    case '快速补给技术':
      title = '快速补给技术';
      description = '快速补给技术提高燃料补给效率，缩短补给时间。';
      category = '军事能源保障';
      sources = ['科研报告', '专利数据'];
      confidence = '中';
      status = '审核中';
      relatedThemes = ['物流技术', '自动化技术'];
      break;
    case '燃料储存技术':
      title = '燃料储存技术';
      description = '燃料储存技术确保燃料在各种环境下的安全储存和长期稳定性。';
      category = '军事能源保障';
      sources = ['期刊论文', '科研报告'];
      confidence = '高';
      status = '已确认';
      relatedThemes = ['材料科学', '安全管理'];
      break;
    case '新能源技术':
      title = '新能源技术';
      description = '新能源技术探索氢能、燃料电池等新型能源在军事领域的应用。';
      category = '军事能源保障';
      sources = ['期刊论文', '科研报告'];
      confidence = '中';
      status = '审核中';
      relatedThemes = ['氢能利用技术', '燃料电池技术'];
      break;
    case '氢能利用技术':
      title = '氢能利用技术';
      description = '氢能利用技术研究氢气的制备、储存和应用技术。';
      category = '军事能源保障';
      sources = ['期刊论文', '科研报告'];
      confidence = '中';
      status = '审核中';
      relatedThemes = ['氢能技术', '能源技术'];
      break;
    case '燃料电池技术':
      title = '燃料电池技术';
      description = '燃料电池技术将化学能直接转化为电能，具有高效、清洁的特点。';
      category = '军事能源保障';
      sources = ['期刊论文', '专利数据'];
      confidence = '中';
      status = '审核中';
      relatedThemes = ['电化学', '能源技术'];
      break;
    // 添加更多主题的详细信息...
    default:
      title = themeName;
      description = '暂无详细描述信息。';
      category = '未分类';
      sources = ['期刊论文'];
      confidence = '未知';
      status = '待审核';
      relatedThemes = [];
  }

  // 生成相关主题的HTML
  let relatedThemesHtml = '';
  if (relatedThemes.length > 0) {
    relatedThemesHtml = '<div class="form-group"><label class="form-label">相关主题</label><div>';
    relatedThemes.forEach(theme => {
      relatedThemesHtml += `<span class="tag tag-secondary mr-2">${theme}</span>`;
    });
    relatedThemesHtml += '</div></div>';
  }

  // 生成识别来源的HTML
  let sourcesHtml = '';
  sources.forEach(source => {
    sourcesHtml += `<span class="tag tag-primary mr-2">${source}</span>`;
  });

  // 生成HTML内容
  return `
    <div class="card">
      <div class="list-item">
        <div>
          <div class="list-title">${title}</div>
          <div class="list-meta">分类: ${category}</div>
        </div>
        <div>
          <span class="status-badge ${status === '已确认' ? 'status-confirmed' : status === '审核中' ? 'status-review' : 'status-new'}">${status}</span>
        </div>
      </div>
      
      <div class="form-group">
        <label class="form-label">主题描述</label>
        <div>${description}</div>
      </div>
      
      <div class="row">
        <div class="col-6">
          <div class="form-group">
            <label class="form-label">识别来源</label>
            <div>${sourcesHtml}</div>
          </div>
        </div>
        <div class="col-6">
          <div class="form-group">
            <label class="form-label">置信度</label>
            <div>${confidence}</div>
          </div>
        </div>
      </div>
      
      ${relatedThemesHtml}
      
      <div class="form-group">
        <button class="btn btn-block btn-secondary" onclick="showThemeAnalysis('${themeName}')">查看分析详情</button>
      </div>
    </div>
  `;
}

// 显示主题分析详情
function showThemeAnalysis(themeName) {
  const content = document.getElementById('modal-theme-detail-content');

  // 显示加载状态
  content.innerHTML = '<div class="loading"><div class="spinner"></div></div>';

  // 模拟数据加载
  setTimeout(() => {
    content.innerHTML = generateThemeAnalysisContent(themeName);
  }, 500);
}

// 生成主题分析详情内容
function generateThemeAnalysisContent(themeName) {
  // 根据主题名称生成不同的分析详情内容
  let title, analysisData;

  switch (themeName) {
    case '防弹衣材料技术':
      title = '防弹衣材料技术分析详情';
      analysisData = {
        "技术成熟度": "8.5/10",
        "应用广度": "高",
        "发展趋势": "稳步上升",
        "关键技术指标": [
          "防护等级: NIJ IIIA",
          "重量: ≤1.2kg",
          "柔韧性: 良好",
          "耐候性: 优异"
        ],
        "主要技术难点": [
          "材料成本控制",
          "多层结构优化",
          "舒适性提升"
        ],
        "典型应用案例": [
          "2023年新型防弹衣项目",
          "特种部队装备升级计划"
        ]
      };
      break;
    case '储能电池技术':
      title = '储能电池技术分析详情';
      analysisData = {
        "技术成熟度": "7.8/10",
        "应用广度": "中",
        "发展趋势": "快速增长",
        "关键技术指标": [
          "能量密度: ≥250Wh/kg",
          "循环寿命: ≥1000次",
          "工作温度: -20°C~60°C",
          "安全性: 通过针刺测试"
        ],
        "主要技术难点": [
          "高能量密度与安全性平衡",
          "低温性能优化",
          "成本控制"
        ],
        "典型应用案例": [
          "野战储能系统项目",
          "单兵电源设备升级"
        ]
      };
      break;
    // 可以为更多主题添加详细分析数据
    default:
      title = `${themeName}分析详情`;
      analysisData = {
        "技术成熟度": "未知",
        "应用广度": "未知",
        "发展趋势": "未知",
        "关键技术指标": [
          "暂无数据"
        ],
        "主要技术难点": [
          "暂无数据"
        ],
        "典型应用案例": [
          "暂无数据"
        ]
      };
  }

  // 生成关键技术指标的HTML
  let keyIndicatorsHtml = '';
  analysisData["关键技术指标"].forEach(indicator => {
    keyIndicatorsHtml += `<div class="list-item"><div>${indicator}</div></div>`;
  });

  // 生成技术难点的HTML
  let challengesHtml = '';
  analysisData["主要技术难点"].forEach(challenge => {
    challengesHtml += `<div class="list-item"><div>${challenge}</div></div>`;
  });

  // 生成应用案例的HTML
  let casesHtml = '';
  analysisData["典型应用案例"].forEach(caseItem => {
    casesHtml += `<div class="list-item"><div>${caseItem}</div></div>`;
  });

  // 生成HTML内容
  return `
    <div class="card">
      <div class="card-header">
        <h3 class="card-title">${title}</h3>
      </div>
      
      <div class="row">
        <div class="col-4">
          <div class="form-group">
            <label class="form-label">技术成熟度</label>
            <div>${analysisData["技术成熟度"]}</div>
          </div>
        </div>
        <div class="col-4">
          <div class="form-group">
            <label class="form-label">应用广度</label>
            <div>${analysisData["应用广度"]}</div>
          </div>
        </div>
        <div class="col-4">
          <div class="form-group">
            <label class="form-label">发展趋势</label>
            <div>${analysisData["发展趋势"]}</div>
          </div>
        </div>
      </div>
      
      <div class="form-group">
        <label class="form-label">关键技术指标</label>
        <div class="card">
          ${keyIndicatorsHtml}
        </div>
      </div>
      
      <div class="form-group">
        <label class="form-label">主要技术难点</label>
        <div class="card">
          ${challengesHtml}
        </div>
      </div>
      
      <div class="form-group">
        <label class="form-label">典型应用案例</label>
        <div class="card">
          ${casesHtml}
        </div>
      </div>
      
      <div class="form-group">
        <button class="btn btn-block btn-secondary" onclick="showThemeDetail('${themeName}')">返回主题详情</button>
      </div>
    </div>
  `;
}

// 显示评估详情弹窗 type 1评估 2详情
function showEvaluationDetailModal(themeName, techpointid, type) { 
  const modal = document.getElementById('evaluation-detail-modal');
  const content = document.getElementById('modal-evaluation-detail-content');
  // 显示加载状态
  content.innerHTML = '<div class="loading"><div class="spinner"></div></div>';
  // 显示弹窗
  modal.style.display = 'flex';
  // content.innerHTML = generateEvaluationDetailContent(themeName, taskId);
  generateEvaluationDetailContent(themeName, techpointid, content, type);
}

// 生成评估详情内容 type 1评估 2详情
function generateEvaluationDetailContent(themeName, techpointid, content, type) {
 
  request('api/Evaluation/getEvaluationDetail', 'POST', {
    tech_point_id: techpointid
  }).then(data => {
    if (data.code === 1) {
      const evaluationList = data.data.evaluationList;
      const techPoint = data.data.techPoint;
      let tech_development_prediction = techPoint.tech_development_prediction;
      tech_development_prediction = tech_development_prediction ? JSON.parse(tech_development_prediction) : {}


      const evaluations = [];
      //遍历替换下面的值
      evaluationList.forEach(item => {
        let temp_evaluations = {
          expertName: item.expert_name,
          time: item.create_time,
          dimensions: [
            { name: "TRL 成熟度（D1）", name_key: 'trl', score: item.trl, value_key: 'trl_comment', comment: item.trl_comment },
            { name: "性能优势（D2）", name_key: 'performance', score: item.performance, value_key: 'performance_comment', comment: item.performance_comment },
            { name: "可靠性（D3）", name_key: 'reliability', score: item.reliability, value_key: 'reliability_comment', comment: item.reliability_comment },
            { name: "采纳度（D10）", name_key: 'adoption', score: item.adoption, value_key: 'adoption_comment', comment: item.adoption_comment },
            { name: "战略契合度（D13）", name_key: 'strategic', score: item.strategic, value_key: 'strategic_comment', comment: item.strategic_comment },
            { name: "E1 战略价值", name_key: 'strategic_value', score: item.strategic_value, value_key: 'strategic_value_comment', comment: item.strategic_value_comment },
            { name: "E2 应用迫切性", name_key: 'urgency', score: item.urgency, value_key: 'urgency_comment', comment: item.urgency_comment },
            { name: "E3 风险可控性", name_key: 'risk', score: item.risk, value_key: 'risk_comment', comment: item.risk_comment },
            { name: "E4 潜在颠覆性", name_key: 'disruptive', score: item.disruptive, value_key: 'disruptive_comment', comment: item.disruptive_comment },
            { name: "E5 协同度", name_key: 'synergy', score: item.synergy, value_key: 'synergy_comment', comment: item.synergy_comment }
          ]
        };
        evaluations.push(temp_evaluations);
      })

      var futureHtmlLook = '';
      // 遍历预测数据，动态生成时间节点
      tech_development_prediction.developmentTrend.forEach(item => {
          const year = Object.keys(item)[0];//取对象的key值
          const year_num = Number(year.replace('years', ''));//years3 取数字 
          const trl = Object.values(item)[0];//取对象的value值 


          // 动态生成HTML
          futureHtmlLook += `
            <div class="timeline-point  future-${year_num}y">
              <div class="point-marker"></div>
              <div class="point-label">${year_num}年后</div>
              <div class="point-value">TRL ${trl}</div>
            </div>
          `;

        });
     
      
      //在前面追加当前状态
      const currentState = tech_development_prediction.currentStatus;//当前状态 TRL 4 
      futureHtmlLook = `
            <div class="timeline-point current">
              <div class="point-marker"></div>
              <div class="point-label">当前状态</div>
              <div class="point-value">TRL ${currentState}</div>
            </div>
          ` + futureHtmlLook;
   
      // 生成评估详情HTML
      let evaluationsHtml = '';
      let topHtml = `<div class="card-header">
                                <h2 class="card-title">识别出的新技术点</h2>
                            </div>
                            <div class="list-item">
                                <div>
                                    <div class="list-title" id="tech-point-title">${techPoint.tech_point_name}</div>
                                    <div class="list-meta" id="tech-point-directory">归属目录: ${techPoint.first_theme_name} > ${techPoint.second_theme_name}</div>
                                </div> 
                            </div> 
                        </div>
                        <div class="card" id="tech-topics-card">
                            <div class="card-header">
                                <h2 class="card-title">识别出的技术主题</h2>
                            </div>
                            <div class="list-item">
                                <div>
                                    <div class="list-title" id="tech-topic-title">${techPoint.second_theme_name}</div>
                                    <div class="list-meta" id="tech-topic-directory">归属目录: ${techPoint.first_theme_name}</div>
                                </div>
                                <div>

                                </div>
                            </div> 
                        </div>
                        <div class="card" id="tech-prediction-card"> 
                            <div class="form-group">
                                <label class="form-label">技术成熟度发展趋势</label>
                                <div class="tech-maturity-timeline">
                                    <div class="timeline-container"> 
                                        <div class="timeline-bar"></div> 
                                        <div id="futurePointsContainerLook" class="timeline-points">
                                            ${futureHtmlLook}
                                        </div>
                                    </div> 
                                </div>
                            </div> 
                        </div> `;



      
      evaluations.forEach(evaluation => {
        let dimensionsHtml = '';
        evaluation.dimensions.forEach(dimension => {
          dimensionsHtml += `
        <div class="form-group">
          <label class="form-label">${dimension.name}</label>
          <div>评分: ${dimension.score}/5</div>
          <div class="mt-1">专家意见: ${dimension.comment}</div>
        </div>
      `;
        });
        evaluationsHtml += ` 
        <div class="card mb-3">
        <div class="card-header">
          <h4 class="card-title">专家: ${evaluation.expertName}</h4>
          <div class="text-muted">评估时间: ${evaluation.time}</div>
        </div>
        <div class="card-body">
          ${dimensionsHtml}
        </div>
      </div>
    `;
      });
       
      content.innerHTML = ` 
     <div class="card">
      ${type == 2 ? topHtml : ''}
      <div class="card-header">
        <h3 class="card-title">${themeName} - 专家评估详情</h3>
      </div>
      <div class="card-body">
        ${evaluationsHtml}
      </div>
      <div class="form-group">
        <button class="btn btn-block btn-secondary" onclick="closeEvaluationDetailModal()">关闭</button>
      </div>
    </div>
  `;
    }
  }).catch(error => {
    console.error('获取评估详情失败:', error);
    showMessage('获取评估详情失败', 'error');
    return;
  });
}

// 关闭评估详情弹窗
function closeEvaluationDetailModal() {
  document.getElementById('evaluation-detail-modal').style.display = 'none';
}

// 初始化专家管理功能
function initExpertManagement() {
  // 检查当前页面是否为系统设置页面
  if (document.body.dataset.page !== 'settings') {
    return;
  }

  // 加载专家列表
  loadExpertList();

  // 绑定添加专家按钮事件
  const addExpertBtn = document.getElementById('add-expert');
  if (addExpertBtn) {
    addExpertBtn.addEventListener('click', showAddExpertModal);
  }
}

// 加载专家列表
function loadExpertList() {
  const expertListContainer = document.getElementById('expert-list');
  if (!expertListContainer) return;

  // 从localStorage获取专家数据，如果没有则使用默认数据
  let experts = JSON.parse(localStorage.getItem('experts') || '[]');

  // 如果没有专家数据，添加默认专家
  if (experts.length === 0) {
    experts = [
      { id: 1, name: '张教授', specialty: '军需保障技术', title: '教授' },
      { id: 2, name: '李博士', specialty: '军事能源技术', title: '博士' },
      { id: 3, name: '王研究员', specialty: '卫勤保障技术', title: '研究员' },
      { id: 4, name: '赵工程师', specialty: '运输投送技术', title: '高级工程师' },
      { id: 5, name: '陈教授', specialty: '军事设施技术', title: '教授' },
      { id: 6, name: '刘博士', specialty: '仓储物流技术', title: '博士' },
      { id: 7, name: '杨研究员', specialty: '后勤大数据技术', title: '研究员' },
      { id: 8, name: '周工程师', specialty: '智能装备技术', title: '高级工程师' },
      { id: 9, name: '吴教授', specialty: '新材料技术', title: '教授' },
      { id: 10, name: '郑博士', specialty: '人工智能技术', title: '博士' }
    ];
    localStorage.setItem('experts', JSON.stringify(experts));
  }

  // 生成专家列表HTML
  let expertsHtml = '';
  experts.forEach(expert => {
    expertsHtml += `
      <div class="list-item">
        <div>
          <div class="list-title">${expert.name}</div>
          <div class="list-meta">${expert.title} | 专业领域: ${expert.specialty}</div>
        </div>
        <div>
          <button class="btn btn-sm btn-secondary edit-expert" data-id="${expert.id}">编辑</button>
          <button class="btn btn-sm btn-warning delete-expert" data-id="${expert.id}">删除</button>
        </div>
      </div>
    `;
  });

  expertListContainer.innerHTML = expertsHtml;

  // 绑定编辑和删除按钮事件
  document.querySelectorAll('.edit-expert').forEach(btn => {
    btn.addEventListener('click', function () {
      const expertId = parseInt(this.dataset.id);
      editExpert(expertId);
    });
  });

  document.querySelectorAll('.delete-expert').forEach(btn => {
    btn.addEventListener('click', function () {
      const expertId = parseInt(this.dataset.id);
      deleteExpert(expertId);
    });
  });
}

// 显示添加专家弹窗
function showAddExpertModal() {
  // 创建弹窗HTML
  const modalHtml = `
    <div class="modal" id="expert-modal" style="display: flex;">
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="card-title">添加专家</h3>
          <button id="close-expert-modal" class="btn btn-sm btn-secondary">关闭</button>
        </div>
        <div class="modal-body">
          <form id="expert-form">
            <div class="form-group">
              <label class="form-label">姓名</label>
              <input type="text" class="input-field" id="expert-name" required>
            </div>
            <div class="form-group">
              <label class="form-label">职称</label>
              <input type="text" class="input-field" id="expert-title" required>
            </div>
            <div class="form-group">
              <label class="form-label">专业领域</label>
              <input type="text" class="input-field" id="expert-specialty" required>
            </div>
            <div class="form-group">
              <button type="submit" class="btn btn-block">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  `;

  // 添加到页面
  document.body.insertAdjacentHTML('beforeend', modalHtml);

  // 绑定关闭按钮事件
  document.getElementById('close-expert-modal').addEventListener('click', function () {
    document.getElementById('expert-modal').remove();
  });

  // 绑定表单提交事件
  document.getElementById('expert-form').addEventListener('submit', function (e) {
    e.preventDefault();
    saveExpert();
  });
}

// 保存专家信息
function saveExpert() {
  const name = document.getElementById('expert-name').value;
  const title = document.getElementById('expert-title').value;
  const specialty = document.getElementById('expert-specialty').value;

  if (!name || !title || !specialty) {
    showMessage('请填写完整信息', 'error');
    return;
  }

  // 获取现有专家数据
  let experts = JSON.parse(localStorage.getItem('experts') || '[]');

  // 生成新的专家ID
  const newId = experts.length > 0 ? Math.max(...experts.map(e => e.id)) + 1 : 1;

  // 添加新专家
  experts.push({
    id: newId,
    name: name,
    title: title,
    specialty: specialty
  });

  // 保存到localStorage
  localStorage.setItem('experts', JSON.stringify(experts));

  // 关闭弹窗
  document.getElementById('expert-modal').remove();

  // 重新加载专家列表
  loadExpertList();

  // 显示成功消息
  showMessage('专家信息已保存', 'success');
}

// 编辑专家信息
function editExpert(expertId) {
  // 获取专家数据
  const experts = JSON.parse(localStorage.getItem('experts') || '[]');
  const expert = experts.find(e => e.id === expertId);

  if (!expert) return;

  // 创建弹窗HTML
  const modalHtml = `
    <div class="modal" id="expert-modal" style="display: flex;">
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="card-title">编辑专家</h3>
          <button id="close-expert-modal" class="btn btn-sm btn-secondary">关闭</button>
        </div>
        <div class="modal-body">
          <form id="expert-form">
            <input type="hidden" id="expert-id" value="${expert.id}">
            <div class="form-group">
              <label class="form-label">姓名</label>
              <input type="text" class="input-field" id="expert-name" value="${expert.name}" required>
            </div>
            <div class="form-group">
              <label class="form-label">职称</label>
              <input type="text" class="input-field" id="expert-title" value="${expert.title}" required>
            </div>
            <div class="form-group">
              <label class="form-label">专业领域</label>
              <input type="text" class="input-field" id="expert-specialty" value="${expert.specialty}" required>
            </div>
            <div class="form-group">
              <button type="submit" class="btn btn-block">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  `;

  // 添加到页面
  document.body.insertAdjacentHTML('beforeend', modalHtml);

  // 绑定关闭按钮事件
  document.getElementById('close-expert-modal').addEventListener('click', function () {
    document.getElementById('expert-modal').remove();
  });

  // 绑定表单提交事件
  document.getElementById('expert-form').addEventListener('submit', function (e) {
    e.preventDefault();
    updateExpert();
  });
}

// 更新专家信息
function updateExpert() {
  const id = parseInt(document.getElementById('expert-id').value);
  const name = document.getElementById('expert-name').value;
  const title = document.getElementById('expert-title').value;
  const specialty = document.getElementById('expert-specialty').value;

  if (!name || !title || !specialty) {
    showMessage('请填写完整信息', 'error');
    return;
  }

  // 获取现有专家数据
  let experts = JSON.parse(localStorage.getItem('experts') || '[]');

  // 更新专家信息
  const index = experts.findIndex(e => e.id === id);
  if (index !== -1) {
    experts[index] = {
      id: id,
      name: name,
      title: title,
      specialty: specialty
    };

    // 保存到localStorage
    localStorage.setItem('experts', JSON.stringify(experts));

    // 关闭弹窗
    document.getElementById('expert-modal').remove();

    // 重新加载专家列表
    loadExpertList();

    // 显示成功消息
    showMessage('专家信息已更新', 'success');
  }
}

// 删除专家
function deleteExpert(expertId) {
  if (!confirm('确定要删除该专家吗？')) {
    return;
  }

  // 获取现有专家数据
  let experts = JSON.parse(localStorage.getItem('experts') || '[]');

  // 删除专家
  experts = experts.filter(e => e.id !== expertId);

  // 保存到localStorage
  localStorage.setItem('experts', JSON.stringify(experts));

  // 重新加载专家列表
  loadExpertList();

  // 显示成功消息
  showMessage('专家已删除', 'success');
}

// 显示专家选择弹窗
// function showExpertSelectionModal(techPoint) {
//   // 获取专家数据
//   const experts = JSON.parse(localStorage.getItem('experts') || '[]');

//   // 如果没有专家数据，提示用户先添加专家
//   if (experts.length === 0) {
//     showMessage('请先在系统设置中添加专家信息', 'error');
//     return;
//   }

//   // 生成专家列表HTML
//   let expertsHtml = '';
//   experts.forEach(expert => {
//     expertsHtml += `
//       <div class="list-item">
//         <div>
//           <div class="list-title">${expert.name}</div>
//           <div class="list-meta">${expert.title} | 专业领域: ${expert.specialty}</div>
//         </div>
//         <div>
//           <input type="checkbox" class="expert-checkbox" data-id="${expert.id}" data-name="${expert.name}">
//         </div>
//       </div>
//     `;
//   });

//   // 创建弹窗HTML
//   const modalHtml = `
//     <div class="modal" id="expert-selection-modal" style="display: flex;">
//       <div class="modal-content">
//         <div class="modal-header">
//           <h3 class="card-title">选择评估专家 - ${techPoint}</h3>
//           <button id="close-expert-selection-modal" class="btn btn-sm btn-secondary">关闭</button>
//         </div>
//         <div class="modal-body">
//           <div class="form-group">
//             <label class="form-label">请选择参与评估的专家（可多选）</label>
//             <div class="card">
//               ${expertsHtml}
//             </div>
//           </div>
//           <div class="form-group">
//             <button class="btn btn-block" id="generate-evaluation-code" data-tech-point="${techPoint}">生成评估码</button>
//           </div>
//         </div>
//       </div>
//     </div>
//   `;

//   // 添加到页面
//   document.body.insertAdjacentHTML('beforeend', modalHtml);

//   // 使用setTimeout确保DOM已更新后再绑定事件
//   setTimeout(() => {
//     // 绑定关闭按钮事件
//     const closeBtn = document.getElementById('close-expert-selection-modal');
//     if (closeBtn) {
//       closeBtn.addEventListener('click', function () {
//         const modal = document.getElementById('expert-selection-modal');
//         if (modal) {
//           modal.remove();
//         }
//       });
//     } else {
//       // 如果直接通过querySelector查找
//       const closeBtnAlt = document.querySelector('#expert-selection-modal .modal-header button');
//       if (closeBtnAlt) {
//         closeBtnAlt.addEventListener('click', function () {
//           const modal = document.getElementById('expert-selection-modal');
//           if (modal) {
//             modal.remove();
//           }
//         });
//       }
//     }

//     // 绑定生成评估码按钮事件
//     const generateBtn = document.getElementById('generate-evaluation-code');
//     if (generateBtn) {
//       generateBtn.addEventListener('click', function () {
//         generateEvaluationCode(techPoint);
//       });
//     } else {
//       // 如果直接通过querySelector查找
//       const generateBtnAlt = document.querySelector('#expert-selection-modal #generate-evaluation-code');
//       if (generateBtnAlt) {
//         generateBtnAlt.addEventListener('click', function () {
//           const techPointAttr = generateBtnAlt.getAttribute('data-tech-point');
//           generateEvaluationCode(techPointAttr);
//         });
//       }
//     }
//   }, 100);
// }

// 生成评估码
function generateEvaluationCode(techPoint) {
  // 获取选中的专家
  const selectedExperts = Array.from(document.querySelectorAll('.expert-checkbox:checked'));

  if (selectedExperts.length === 0) {
    showMessage('请至少选择一位专家', 'error');
    return;
  }

  // 生成4位随机数字评估码
  const evaluationCode = Math.floor(1000 + Math.random() * 9000);

  // 获取选中的专家信息
  const expertNames = selectedExperts.map(checkbox => checkbox.dataset.name).join(', ');

  // 创建评估码显示弹窗
  const modalHtml = `
    <div class="modal" id="evaluation-code-modal" style="display: flex;">
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="card-title">评估码已生成</h3>
          <button id="close-evaluation-code-modal" class="btn btn-sm btn-secondary">关闭</button>
        </div>
        <div class="modal-body">
          <div class="form-group text-center">
            <label class="form-label">技术点: ${techPoint}</label>
            <div class="mt-2">
              <label class="form-label">评估专家: ${expertNames}</label>
            </div>
            <div class="mt-3">
              <label class="form-label">评估码</label>
              <div class="evaluation-code-display">${evaluationCode}</div>
            </div>
            <div class="mt-3">
              <button class="btn btn-block btn-secondary" id="copy-evaluation-code">复制评估码</button>
            </div>
            <div class="mt-3 text-warning">
              请妥善保存评估码，专家需要此码进行评估
            </div>
          </div>
        </div>
      </div>
    </div>
  `;

  // 添加到页面
  document.body.insertAdjacentHTML('beforeend', modalHtml);

  // 保存评估码到全局变量，以便在事件处理函数中访问
  window.currentEvaluationCode = evaluationCode;

  // 使用setTimeout确保DOM已更新后再绑定事件
  setTimeout(() => {
    // 绑定关闭按钮事件
    const closeBtn = document.getElementById('close-evaluation-code-modal');
    if (closeBtn) {
      closeBtn.addEventListener('click', function () {
        const codeModal = document.getElementById('evaluation-code-modal');
        if (codeModal) {
          codeModal.remove();
        }
        // 同时关闭专家选择弹窗
        const expertModal = document.getElementById('expert-selection-modal');
        if (expertModal) {
          expertModal.remove();
        }
        // 清除全局变量
        window.currentEvaluationCode = null;
      });
    } else {
      // 如果直接通过querySelector查找
      const closeBtnAlt = document.querySelector('#evaluation-code-modal .modal-header button');
      if (closeBtnAlt) {
        closeBtnAlt.addEventListener('click', function () {
          const codeModal = document.getElementById('evaluation-code-modal');
          if (codeModal) {
            codeModal.remove();
          }
          // 同时关闭专家选择弹窗
          const expertModal = document.getElementById('expert-selection-modal');
          if (expertModal) {
            expertModal.remove();
          }
          // 清除全局变量
          window.currentEvaluationCode = null;
        });
      }
    }

    // 绑定复制评估码按钮事件
    const copyButton = document.getElementById('copy-evaluation-code');
    if (copyButton) {
      copyButton.addEventListener('click', function () {
        // 复制评估码到剪贴板
        navigator.clipboard.writeText(window.currentEvaluationCode).then(() => {
          showMessage('评估码已复制到剪贴板', 'success');
        }).catch(() => {
          showMessage('复制失败，请手动记录评估码', 'error');
        });
      });
    } else {
      // 如果直接通过querySelector查找
      const copyButtonAlt = document.querySelector('#evaluation-code-modal #copy-evaluation-code');
      if (copyButtonAlt) {
        copyButtonAlt.addEventListener('click', function () {
          // 复制评估码到剪贴板
          navigator.clipboard.writeText(window.currentEvaluationCode).then(() => {
            showMessage('评估码已复制到剪贴板', 'success');
          }).catch(() => {
            showMessage('复制失败，请手动记录评估码', 'error');
          });
        });
      }
    }
  }, 100);
}

//生成评估码
function generateEvaluationCode() {
  //获取参数
  const urlParams = new URLSearchParams(window.location.search);
  const taskId = urlParams.get('id');//任务id
  if (!taskId) {
    showMessage('任务ID不存在', 'error');
    return;
  }
  request('api/Task/createEvaluationCode', 'POST', { id: taskId }).then(data => {
    if (data.code === 1) {
      showMessage('评估码已生成', 'success');
      //更新页面
      initTaskResultsPageData();
    } else {
      showMessage(data.msg || '生成失败', 'error');
    }
  });

}

var pointDetail = {};//技术点详情
// 初始化任务结果页面功能
function initTaskResultsPageData() {
  // 检查当前页面是否为任务结果页面
  if (!document.body.dataset.page || !document.body.dataset.page.startsWith('task-results')) {
    return;
  }
  //获取参数
  const urlParams = new URLSearchParams(window.location.search);
  const taskId = urlParams.get('id');//任务id

  request('api/Task/getTaskDetail', 'POST', { id: taskId }).then(data => {
    if (data.code === 1) {
      const taskDetail = data.data;

      let resObj = taskDetail.model_outputs && taskDetail.model_outputs.outputs && taskDetail.model_outputs.outputs.result ? taskDetail.model_outputs.outputs.result : {};
      // 任务基本信息
      const taskInfo = resObj && resObj.taskInfo ? resObj.taskInfo : {};
      // 分析流程
      const process = resObj && resObj.analysisProcess ? resObj.analysisProcess : { steps: [], progress: 10 };
      // 统计
      const stat = resObj && resObj.statistics ? resObj.statistics : {};
      // 技术点列表
      const techPoints = resObj && resObj.techPoints ? resObj.techPoints : [];
      pointDetail = techPoints

      //当前系统组装的技术点
      const tech_points = taskDetail['tech_points'];

      // 预测依据
      const basis = resObj && resObj.predictionBasis ? resObj.predictionBasis : [];

      // 1. 刷新顶部任务卡片
      const taskTitle = document.getElementById('task-title');
      if (taskTitle) {
        taskTitle.textContent = taskInfo.title || '任务名称';
      }
      // 刷新执行时间
      const executionTime = document.getElementById('execution-time');
      if (executionTime) {
        executionTime.textContent = taskInfo.executionTime || '执行时间';
      }
      //任务ID
      document.getElementById('task-evaluation-code').textContent = taskDetail.no;
      // 填充状态
      const taskStatus = document.getElementById('task-status');
      if (taskStatus) {
        if (taskDetail.state === 1) {
          taskStatus.innerHTML = `
            <div><span class="status-badge  status-jxz">已提交到大模型</span></div>
          `;
        } else if (taskDetail.state === 2) {
          let temp_innerHTML = `
            <div style="margin-top:10px"><span class="status-badge status-confirmed">大模型分析完成</span></div>
          `;

          if (taskDetail.assess_state == 1) {
            temp_innerHTML += `
              <div style="margin-top:10px"><span class="status-badge status-jxz">待专家评估</span></div>
            `;
          }
          else if (taskDetail.assess_state == 2) {
            temp_innerHTML += `
              <div style="margin-top:10px"><span class="status-badge status-jxz">专家评估中</span></div>
            `;
          }
          else if (taskDetail.assess_state == 3) {
            temp_innerHTML += `
              <div style="margin-top:10px"><span class="status-badge status-confirmed">专家已评估完成</span></div>
            `;
          }
          taskStatus.innerHTML = temp_innerHTML;
        }
      }


      // 2. 刷新进度条progress-bar
      const progressBar = document.querySelector('#progress-bar .progress-inner');
      const progressText = document.getElementById('progress-text');
      if (progressBar) {
        progressBar.style.width = process.progress + '%';
      }
      if (progressText) {
        progressText.textContent = process.progress + '%';
      }
      // 2. 刷新开始时间和结束时间
      const startTime = document.getElementById('start-time');
      const endTime = document.getElementById('end-time');
      if (startTime) startTime.textContent = process.startTime || '开始时间';
      if (endTime) endTime.textContent = process.endTime || '结束时间';

      // 3. 刷新步骤列表
      const stepList = document.getElementById('analysis-steps');
      if (stepList) {
        // 清空旧内容
        stepList.innerHTML = '';
        process.steps.forEach(step => {
          const progressItem = document.createElement('div');
          progressItem.className = 'progress-item';
          progressItem.innerHTML = `
              <div class="progress-title">${step.title}</div>
              <div class="progress-meta">
                <span class="progress-status status-${step.status === 'completed' ? 'completed' : 'review'}">
                  ${step.status === 'completed' ? '已完成' : '进行中'}
                </span>
                <span style="float: right;">${step.timeRange}</span>
              </div>
            `;
          stepList.appendChild(progressItem);
        });
      }

      // 4. 刷新统计
      const statNewTech = document.getElementById('new-tech-point-count');//新增技术点数量
      const statTopic = document.getElementById('tech-topic-count');//技术主题数量
      const statPending = document.getElementById('pending-assess-count');//待评估数量
      if (statNewTech) statNewTech.textContent = stat.newTechPointCount;
      if (statTopic) statTopic.textContent = stat.techTopicCount;
      if (statPending) statPending.textContent = stat.pendingAssessCount;


      // 5. 刷新技术点列表
      // 重组技术点格式
      const techPointsList = techPoints.map(item => item.techPoint);
      //重组技术水平预测 
      // 刷新技术点列表
      const techList = document.getElementById('tech-points-list');
      if (techList) {
        techList.innerHTML = '';
        tech_points.forEach(item => {
          const tp = item;
          const tr = document.createElement('div');
          tr.className = 'list-item';
          let html = `
              <div>
                <div class="list-title">${tp.tech_point_name}</div>
                <div class="list-meta">归属目录: ${tp.first_theme_name} > ${tp.second_theme_name}</div>
              </div>
              <div>`;
          // 如果专家数为0，则显示发起评估按钮
          if (!tp.experts_num) {
            html += `
                <button class="btn btn-sm start-evaluation btn-start-evaluation" data-evaluation-code="${taskDetail.evaluation_code}" data-tech-point="${tp.id}">发起评估</button>`;
          }
          html += `
              </div>`;
          tr.innerHTML = html;
          techList.appendChild(tr);
          // 绑定发起评估按钮事件
          document.querySelectorAll('.start-evaluation').forEach(button => {
            button.addEventListener('click', function () {
              //检查是否已生成评估码
              const evaluationCode = this.dataset.evaluationCode;
              const techPointId = this.dataset.techPoint;

              //获取参数
              const urlParams = new URLSearchParams(window.location.search);
              const taskId = urlParams.get('id');//任务id

              if (!evaluationCode) {
                showMessage('请先生成评估码', 'error');
                return;
              } else {
                document.getElementById('task_task_id').value = taskId;
                document.getElementById('task_tech_point_id').value = techPointId;
                document.getElementById('task_evaluation_code').value = evaluationCode;
                expertCountModal.style.display = 'block';
              }
            });
          });
        });
      }
      // 5. 刷新技术选择器
      const techSelector = document.getElementById('tech-selector');
      if (techSelector) {
        techSelector.innerHTML = '';
        techPointsList.forEach(item => {
          const tp = item;
          const option = document.createElement('option');
          option.value = tp.techPointId;
          option.textContent = tp.techPointName;
          techSelector.appendChild(option);
        });
      }

      // 6. 刷新预测依据
      const basisList = document.getElementById('prediction-basis');
      if (basisList) {
        basisList.innerHTML = '';
        basis.forEach(b => {
          //预测依据
          const div = document.createElement('div');
          div.className = 'basis-item';
          div.innerHTML = `
               <div class="basis-title">${b.title}</div>
               <div class="basis-content">${b.content}</div>
             `;
          basisList.appendChild(div);
        });
      }
      updateTechMaturityPrediction();



      document.getElementById('evaluationCode117').textContent = taskDetail.evaluation_code;
      if (taskDetail.evaluation_code) {
        document.getElementById('generateCode117').style.display = 'none';
      }
      document.querySelector('.btn-start-evaluation').dataset.evaluationCode = taskDetail.evaluation_code;
      // 绑定发起评估按钮事件

      if (taskDetail.state == 1) {//已提交到大模型
        // 显示所有卡片
        document.getElementById('analysis-card').style.display = 'none';//分析过程 
        document.getElementById('evaluation-code-card').style.display = 'none';//评估码保存
        document.getElementById('tech-prediction-card').style.display = 'none';//技术发展水平预测    
        document.querySelector('.btn-start-evaluation').style.display = 'none';//发起评估按钮
      } else if (taskDetail.state == 2) {//大模型分析完成

        if (taskDetail.assess_state == 0) { //0.未发起评估 1.待评估 2、专家评估中 3.已评估
          // document.getElementById('analysis-card').style.display = 'none';//分析过程
          // document.getElementById('stats-card').classList.remove('d-none');//识别结果统计
          // document.getElementById('tech-points-card').classList.remove('d-none');//识别出的新技术点
          // document.getElementById('tech-topics-card').classList.remove('d-none');//识别出的技术主题
          // document.getElementById('evaluation-code-card').style.display = 'none';//评估码保存
          // document.getElementById('tech-prediction-card').style.display = 'none';//技术发展水平预测  
        } else { //待评估或者评估中或者已评估
          // document.getElementById('analysis-card').style.display = 'none';//分析过程
          // document.getElementById('stats-card').style.display = 'none';//识别结果统计
          // document.getElementById('tech-points-card').style.display = 'none';//识别出的新技术点
          // document.getElementById('tech-topics-card').style.display = 'none';//识别出的技术主题
          document.getElementById('evaluation-code-card').style.display = 'none';//评估码保存
          // document.getElementById('tech-prediction-card').style.display = 'none';//技术发展水平预测  
        }
      }
    }
  }).catch(error => {
    console.error('获取任务详情失败:', error);
  });

  // const startEvaluationButtons = document.querySelectorAll('.start-evaluation');
  // startEvaluationButtons.forEach(button => {
  //   button.addEventListener('click', function () {
  //     const techPoint = this.dataset.techPoint;
  //     const theme = this.dataset.theme;

  //     // 跳转到评估页面并传递参数
  //     if (techPoint) {
  //       window.location.href = `evaluation.html?techPoint=${encodeURIComponent(techPoint)}`;
  //     } else if (theme) {
  //       window.location.href = `evaluation.html?theme=${encodeURIComponent(theme)}`;
  //     }
  //   });
  // });







  // 初始化技术发展水平预测图表
  initTechMaturityPrediction();
}

//发起评估方法
function startEvaluationFun(taskId, expertCount, evaluationCode, techPointId) {
  request('api/Task/updateTask', 'POST', { 'id': taskId, 'experts_num': expertCount, 'tech_point_id': techPointId }).then(data => {
    if (data.code === 1) {
      showMessage('保存成功');
      window.location.href = `evaluation.html?evaluationCode=${encodeURIComponent(evaluationCode)}&expertCount=${encodeURIComponent(expertCount)}`;
    } else {
      showMessage('保存失败', 'error');
    }
  }).catch(error => {
    // showMessage('保存失败', 'error');
  });
}

//提交评估方法
function taskSubmitEvaluation() {
  const taskId = document.getElementById('task_task_id').value;
  const techPointId = document.getElementById('task_tech_point_id').value;//这个技术点是本系统的技术点ID 不是模型返的技术点ID
  const expertCount = document.getElementById('newExpertCount').value;
  const evaluationCode = document.getElementById('task_evaluation_code').value;

  startEvaluationFun(taskId, expertCount, evaluationCode, techPointId);
}

// 初始化技术发展水平预测
function initTechMaturityPrediction() {
  // 这里可以添加动态数据加载逻辑
  // 目前使用静态数据展示
  // console.log('技术发展水平预测功能已初始化');

  // 绑定技术选择事件
  const techSelector = document.getElementById('tech-selector');
  if (techSelector) {
    techSelector.addEventListener('change', updateTechMaturityPrediction);
  }

  // 初始化时更新一次预测数据
  // updateTechMaturityPrediction();
}

// 更新技术成熟度预测图表
function updateTechMaturityPrediction() {

  const techSelector = document.getElementById('tech-selector');
  if (!techSelector) return;

  let selectedTech = techSelector.value;//获取选中的技术点 
  //获取当前技术点下的 时间线
  var tempPointData = pointDetail ? pointDetail.map(item => item.techPoint) : [];
  // 若未选中技术点且存在技术点数据，则默认选中第一个；否则保持未选中状态
  if (!selectedTech || selectedTech == 'undefined') {
    selectedTech = tempPointData[0].techPointId;
  }

  //根据技术点id获取
  let selectedPoint = tempPointData.find(point => point.techPointId == selectedTech);

  let techDevelopmentPrediction = selectedPoint.techDevelopmentPrediction ? selectedPoint.techDevelopmentPrediction : [];
  const futurePointsContainer = document.getElementById('future-points-container');
  if (!futurePointsContainer) return;
  // 清空之前的内容
  futurePointsContainer.innerHTML = '';
  var futureHtml = '';
  // 遍历预测数据，动态生成时间节点
  techDevelopmentPrediction.developmentTrend.forEach(item => {
    const year = Object.keys(item)[0];//取对象的key值
    const year_num = Number(year.replace('years', ''));//years3 取数字 
    const trl = Object.values(item)[0];//取对象的value值 


    // 动态生成HTML
    futureHtml += `
      <div class="timeline-point  future-${year_num}y">
        <div class="point-marker"></div>
        <div class="point-label">${year_num}年后</div>
        <div class="point-value">TRL ${trl}</div>
      </div>
    `;

  });
  //在前面追加当前状态
  const currentState = techDevelopmentPrediction.currentStatus;//当前状态 TRL 4 
  futureHtml = `
        <div class="timeline-point current">
          <div class="point-marker"></div>
          <div class="point-label">当前状态</div>
          <div class="point-value">TRL ${currentState}</div>
        </div>
      ` + futureHtml;
  // 插入到容器中
  futurePointsContainer.insertAdjacentHTML('beforeend', futureHtml);


  return;
  const currentPoint = document.querySelector('.timeline-point.current .point-value');
  const future3YPoint = document.querySelector('.timeline-point.future-3y .point-value');
  const future5YPoint = document.querySelector('.timeline-point.future-5y .point-value');
  const future10YPoint = document.querySelector('.timeline-point.future-10y .point-value');

  // 根据选择的技术更新预测数据
  let currentTRL, future3YTRL, future5YTRL, future10YTRL;

  switch (selectedTech) {
    case 'adaptive-energy':
      currentTRL = 3;
      future3YTRL = 5;
      future5YTRL = 6;
      future10YTRL = 9;
      break;
    case 'smart-materials':
      currentTRL = 4;
      future3YTRL = 6;
      future5YTRL = 7;
      future10YTRL = 9;
      break;
    case 'distributed-medical':
      currentTRL = 3;
      future3YTRL = 5;
      future5YTRL = 6;
      future10YTRL = 8;
      break;
    case 'quantum-encryption':
      currentTRL = 2;
      future3YTRL = 4;
      future5YTRL = 5;
      future10YTRL = 7;
      break;
    case 'precision-navigation':
      currentTRL = 5;
      future3YTRL = 7;
      future5YTRL = 8;
      future10YTRL = 9;
      break;
    default:
      currentTRL = 3;
      future3YTRL = 5;
      future5YTRL = 6;
      future10YTRL = 9;
  }

  // 更新界面显示
  if (currentPoint) currentPoint.textContent = `TRL ${currentTRL}`;
  if (future3YPoint) future3YPoint.textContent = `TRL ${future3YTRL}`;
  if (future5YPoint) future5YPoint.textContent = `TRL ${future5YTRL}`;
  if (future10YPoint) future10YPoint.textContent = `TRL ${future10YTRL}`;

  // 更新预测依据说明
  updatePredictionBasis(selectedTech);
}

// 更新预测依据说明
function updatePredictionBasis(techType) {
  const basisContentElements = document.querySelectorAll('.basis-content');
  if (basisContentElements.length < 3) return;

  let basis1, basis2, basis3;

  switch (techType) {
    case 'adaptive-energy':
      basis1 = '根据同类技术发展历史数据分析，该技术年均成熟度提升约0.3级';
      basis2 = '预计未来5年该领域研发投入将增长40%，将显著加速技术发展';
      basis3 = '军事应用需求强烈，将推动技术快速向实战化转化';
      break;
    case 'smart-materials':
      basis1 = '该技术已具备较好的研究基础，年均成熟度提升约0.4级';
      basis2 = '材料科学领域突破性进展将推动该技术快速发展';
      basis3 = '军民融合发展战略将为该技术提供广阔应用场景';
      break;
    case 'distributed-medical':
      basis1 = '医疗AI技术快速发展，将带动该技术年均成熟度提升0.35级';
      basis2 = '卫勤保障需求迫切，将获得持续研发投入支持';
      basis3 = '5G通信技术成熟将为该技术提供良好的网络基础';
      break;
    case 'quantum-encryption':
      basis1 = '量子技术处于前沿探索阶段，年均成熟度提升约0.25级';
      basis2 = '国家高度重视量子科技发展，将持续加大投入';
      basis3 = '信息安全需求将推动该技术加速向实用化发展';
      break;
    case 'precision-navigation':
      basis1 = '导航定位技术相对成熟，年均成熟度提升约0.3级';
      basis2 = '芯片技术进步将提升该技术的精度和可靠性';
      basis3 = '无人系统广泛应用将为该技术提供强劲市场需求';
      break;
    default:
      basis1 = '根据同类技术发展历史数据分析，该技术年均成熟度提升约0.3级';
      basis2 = '预计未来5年该领域研发投入将增长40%，将显著加速技术发展';
      basis3 = '军事应用需求强烈，将推动技术快速向实战化转化';
  }

  basisContentElements[0].textContent = basis1;
  basisContentElements[1].textContent = basis2;
  basisContentElements[2].textContent = basis3;
}

// 页面加载完成后初始化任务结果页面功能
document.addEventListener('DOMContentLoaded', function () {
  initTaskResultsPage();
});
